使用BeautifulSoup模块可以轻松地从HTML或XML文件中提取信息。要按条件通过类名抓取项,请使用find_all()方法和CSS选择器。
例如,我们要通过类名为“title”的元素来获取某个网页的所有标题。我们可以使用以下代码:
from bs4 import BeautifulSoup
import requests
response = requests.get('http://example.com')
soup = BeautifulSoup(response.content, 'html.parser')
titles = soup.find_all("div", class_="title")
for title in titles:
print(title.text)
在上面的代码中,我们首先使用requests模块获取网页的内容,然后使用BeautifulSoup解析HTML内容。然后,我们使用find_all()方法并指定CSS选择器,即包含class为“title”的div元素。最后,我们使用for循环遍历所有标题,并打印它们的文本。
请注意,我们使用class_参数来指定CSS类名,因为“class”是Python中的保留关键字。