BeautifulSoup的HTML解析器默认会修改标签的href属性。如果不想修改href属性,可以使用lxml库作为解析器。
下面是使用lxml库作为解析器的代码示例:
from bs4 import BeautifulSoup
import requests
# 请求网页内容
url = 'https://example.com'
response = requests.get(url)
html_content = response.text
# 使用lxml库作为解析器
soup = BeautifulSoup(html_content, 'lxml')
# 解析HTML内容
links = soup.find_all('a')
for link in links:
# 获取href属性值
href = link.get('href')
print(href)
在上面的示例中,我们将'lxml'作为解析器传递给BeautifulSoup对象,这样就可以使用lxml库进行HTML解析。然后,我们使用find_all方法找到所有的a标签,并使用get方法获取href属性的值,而不会修改href属性。