爬虫模板要求爬取新闻包括标题人名地名等
以下是一个简单的爬虫模板,可以用于爬取新闻网站的标题、作者、发布日期、正文和相关地名等信息:
import requests
from bs4 import BeautifulSoup
import re
url = "https://www.example.com/news" # 更改为目标网站的新闻页面URL
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
for article in soup.find_all("article"):
# 获取标题
title = article.find("h2").text.strip()
# 获取作者
author = article.find("span", class_="author").text.strip()
# 获取发布日期
date = article.find("span", class_="date").text.strip()
# 获取正文
content = article.find("div", class_="content").text.strip()
# 获取相关地名
locations = re.findall(r"\b[A-Z][a-z]+(?: [A-Z][a-z]+)*\b", content)
# 打印结果
print("标题:", title)
print("作者:", author)
print("发布日期:", date)
print("正文:", content)
print("相关地名:", locations)
print("-" * 50)
需要注意的是,不同的新闻网站可能有不同的HTML结构和类名,需要根据具体情况进行调整。另外,获取地名的正则表达式也需要根据实际情况进行修改
原文地址: https://www.cveoy.top/t/topic/dHAP 著作权归作者所有。请勿转载和采集!