import requests
import re
from datetime import datetime
def baidu(company):
#第一步:模拟浏览器,在百度引擎中输入相应的企业,并且得到网页源代码
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'}
url = 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&ie=utf-8&word='+ company
res = requests.get(url,headers = headers).text
#第二步:正则表达式提取所需信息
p_href = '<h3 class="news-title_1YtI1"><a href="(.*?)"'
p_title = '<h3 class="news-title_1YtI1">.*?<!--s-text-->(.*?)<!--/s-text-->'
p_source = '<div class="news-source">.*?<span class="c-color-gray c-font-normal c-gap-right">(.*?)</span>'
p_date = '<div class="news-source">.*?<span class="c-color-gray2 c-font-normal">(.*?)</span>'
href = re.findall(p_href,res,re.S)
title = re.findall(p_title,res,re.S)
source = re.findall(p_source,res,re.S)
date = re.findall(p_date,res,re.S)
#第三步:信息的清洗
for i in range(len(title)):
title[i] = title[i].strip()
title[i] = re.sub('<.*?>','',title[i])
source[i] = source[i].strip()
date[i] = date[i].strip()
#第四步:自动生成数据报告
time = datetime.now().strftime('%Y-%m-%d')
file_path = 'C:\\Users\\1\\Desktop\\Python\\爬虫实验555'+ '('+ time + ')'
file1 = open(file_path + '.txt','a')
file1.write('\n'+ company + '数据爬取开始了!'+ '\n'+ '\n')
#第五步:输出爬取信息到数据报告中
for i in range(len(title)):
file1.write(str(i+1) + '.'+ title[0]+ '(' + date[i] + '-' + source[i] + ')' + '\n')
file1.write(href[i] + '\n')
file1.write('-'*40)
file1.close()
companys = ['阿里巴巴','万科集团','百度集团','美团','饿了吗']
for i in companys:
baidu(i)
print(i + '百度新闻数据爬取结束!')
1.最重要的是!!第一步的获取源代码中肯定需要要实现翻页,通过信息提取直到100条为止
2.剩下的信息提取和报告输出按部就班即可。