在BeautifulSoup中要正确使用class和href属性,可以使用如下代码示例:
from bs4 import BeautifulSoup
html_doc = """
BeautifulSoup Example
Example Website
This is an example website.
"""
# 找到class属性为"article"的div标签内的所有a标签
soup = BeautifulSoup(html_doc, 'html.parser')
article_div = soup.find('div', class_='article')
links = article_div.find_all('a')
# 输出结果
for link in links:
print(link.get('href'))
解释:在查找class属性时,应该使用class_而不是class关键字,以避免与Python中的class关键字冲突。在获取href属性时,应该使用get方法获取属性的值。