找到包头新闻网的地址,右键找到检查打开,就开始接下来的操作了
思路:先找到每条新闻的url,写一个方法,当每次传入这个url的时候,我们抓取标题、文章内容、发布时间以及作者,保存到字典 中,并且返回这个字典。然后将每条消息的数据(字典内容)放到列表中,最后利用pandas中的dataframe清洗成我们想要 的数据写出到Excel中,这样的数据直接可以进行分析
import requests
from bs4 import BeautifulSoup
import pprint
def getArticle(url):
# 创建字典,保存接下来的新闻信息
info = {}
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text,'html.parser')
# 获取新闻标题,写入字典
info['标题'] = soup.select('.article-main h1')[0].text.strip()
# 获取文章数据,将文章中多余空格清除并且放到string列表中,写入字典
info['文章'] = ' '.join(soup.select('.article-content')[0].text.split())
# 获取文章发布时间,写入字典
info['发布时间'] = soup.select('.article-infos time')[0].text
# 获取编辑作者,写入字典
info['编辑'] = soup.select('.editors')[0].text.split(':')[1]
# 获取负责编辑,写入字典
info['负责编辑'] = soup.select('.editors')[1].text.split(':')[1]
# 将字典返回
return info
# getArticle('http://www.baotounews.com.cn/szyw/p/680359.html')
# 创建列表
newsary = []
res = requests.get('http://www.baotounews.com.cn/xinwen')
res.encoding = 'utf-8'
# print(res.text)
soup = BeautifulSoup(res.text,'html.parser')
for link in soup.select('.left-square-con a'):
# 获取url
url = link['href']
# 将返回的字典数据写到列表中
newsary.append(getArticle(url))
# pprint.pprint(newsary)
# 转化为dataframe进行清洗
import pandas
# 设置行不限制数量,不然会中间有省略号,数据会看不到
pandas.set_option('display.max_rows', None)
# 设置列不限制数量,不然会中间有省略号,数据会看不到
pandas.set_option('display.max_columns', None)
# 控制台输出的列数超过1000换行,不然数据表格会折回来
pandas.set_option('display.width', 1000)
df = pandas.DataFrame(newsary)
# 如果我们要对dataframe中某列数据进行清洗,我们可以使用匿名函数lambda
# df['标题'] = df['标题'].map(lambda e : e.split())
# 如果我们要重新编排列的顺序:
df = df[['标题','文章','编辑','负责编辑','发布时间']]
# print(df.head())
# 写出到Excel中
df.to_excel('C:\\Users\\lenovo\\Desktop\\BTnews.xlsx')
print('程序执行完毕')
结果