要使用BeautifulSoup来爬取一些文章,但不爬取其他文章,你可以使用BeautifulSoup的select方法结合CSS选择器来定位所需的文章。
以下是一个示例代码,假设你想从一个新闻网站上爬取标题为"Sports"的所有文章:
from bs4 import BeautifulSoup
import requests
# 发送GET请求获取网页内容
url = "https://example.com/news" # 替换为你要爬取的网站URL
response = requests.get(url)
html_content = response.text
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(html_content, "html.parser")
# 使用CSS选择器定位所有标题为"Sports"的文章
articles = soup.select("h2:contains('Sports')") # 替换为正确的CSS选择器
# 打印所有找到的文章标题和链接
for article in articles:
title = article.text
link = article.a["href"]
print(f"标题:{title},链接:{link}")
在上面的示例中,我们首先发送一个GET请求来获取网页的内容。然后,我们使用BeautifulSoup解析网页内容,并使用CSS选择器定位所有标题为"Sports"的文章。最后,我们遍历找到的文章,并打印它们的标题和链接。
请注意,你需要根据实际情况修改示例代码中的URL和CSS选择器,以适应你要爬取的网站的结构和要求。