一、背景
疫情期间,每天需要搜集新冠肺炎相关新闻,编写了一个python脚本用户爬取新浪网相关新闻
二、实例解析
- 模块:requests、BeautifulSoup、re
- url:https://search.sina.com.cn/?q=新冠&c=news&sort=time
1.初始化
- 定义一个GetNews类,在__init__中写入初始化参数
class GetNews:
def __init__(self,keyword,name):
self.headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74',
'Referer':'https://search.sina.com.cn/'
}
self.keyword=keyword
self.txtname=name
self.news_url=[] #存储每条新闻的url
self.news_title=[] #存储每条新闻的标题
self.news_content=[] #存储新闻内容
self.news_time=[] #存储新闻的发表时间
self.page_cout=0 #搜索结果的页码
2.获取搜索结果的页码
- 如上图所示,新浪的搜索结果是分页保存的,先获取搜索结果的总页数,可用于后续爬取所以相关新闻。
def get_page_cout(self):
url = 'https://search.sina.com.cn/?q={0}&c=news&from=channel&ie=utf-8'.format(self.keyword) #查找的关键字url
response = requests.get(url)
response.encoding = 'utf-8'
html =response.text
soup =BeautifulSoup(html,'lxml'<