使用BeautifulSoup4库的find_all()方法可以深入查找文章。以下是一个示例代码:
from bs4 import BeautifulSoup
import requests
# 获取网页内容
url = "https://example.com"
response = requests.get(url)
content = response.content
# 创建BeautifulSoup对象
soup = BeautifulSoup(content, "html.parser")
# 使用find_all方法查找所有的文章标题
article_titles = soup.find_all("h2", class_="article-title")
# 打印所有的文章标题
for title in article_titles:
print(title.text)
这段代码首先使用requests
库获取网页的内容,然后使用BeautifulSoup
库创建一个BeautifulSoup对象soup
。接下来,使用find_all方法来查找网页中所有的文章标题,并将结果存储在article_titles
变量中。最后,通过遍历article_titles
变量,打印出所有的文章标题。
请注意,在实际使用中,你需要根据你要爬取的网页的HTML结构和内容,调整find_all方法的参数以匹配你要查找的文章标题的标签和类名。