爬取财经新闻+新闻评论(一网打尽)
第一篇csdn!应用性比较强的爬虫(投资者情绪+自然语言处理+动态传输/网页)包括阅读量、评论量、文章来源、新闻标题、新闻正文、对于新闻的评论数、对于新闻的评论研一新生,时间紧任务重,有需要的代码及讲解的麻烦点赞或者收藏哦,我会火速在下一片csdn中张贴出代码及讲解,后期有可能也会在b站上做更多的分享...
·
第一篇csdn!
应用性比较强的爬虫(投资者情绪+自然语言处理+动态传输/网页)
包括阅读量、评论量、文章来源、新闻标题、新闻正文、对于新闻的评论数、对于新闻的评论
研一新生,时间紧任务重,有需要的代码及讲解的麻烦点赞或者收藏哦,我会火速在下一篇csdn中张贴出代码及讲解,后期有可能也会在b站上做更多的分享
时隔多日,一直在忙自己的科研,现在终于小小地突破了下瓶颈,抓紧给大家分享
爬虫大致分为两部分:基本信息的爬取(正文相关)&动态传输的爬取(评论相关)
一、基本信息
包括新闻标题、新闻正文、发表时间、发表来源、评论量、阅读量、新闻链接
from random import random
from time import sleep
import random
import openpyxl
import requests
from bs4 import BeautifulSoup
from lxml import etree
import math
import re
import xlsxwriter
def get_url(pages1):
'''
获取资讯链接列表
pages1是值爬取页数
'''
url_list = []
for page in range(1, pages1 + 1): # 左闭右开
url = f"http://guba.eastmoney.com/list,600519,1,f_{page}.html" # 首f和{page}交相呼应
url_list.append(url) # 将每一个链接储存在列表立
return url_list # 返回列表
def get_news(url_list):
ILLEGAL_CHARACTERS_RE = re.compile(r'[\000-\010]|[\013-\014]|[\016-\037]') # 剥离非法字符串
'''
获取新闻列表至本地xls
url_list是指链接列表
'''
headers2 = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15'
} # 头信息很重要,在每个网页源代码里面寻找
# 保存爬取内容
outwb = openpyxl.Workbook() # 打开一个将写的文件
outws = outwb.create_sheet(index=0) # 在将写的文件创建sheet,index只能为0
# 相当于创建表格首行
outws.cell(row=1, column=1, value="read")
outws.cell(row=1, column=2, value="comment")
outws.cell(row=1, column=3, value="title")
outws.cell(row=1, column=4, value="author")
outws.cell(row=1, column=5, value="renew")
outws.cell(row=1, column=6, value="link")
outws.cell(row=1, column=7, value="source")
outws.cell(row=1, column=8, value="body")
outws.cell(row=1, column=9, value="article_reply_counts")
outws.cell(row=1,column=10,value="article_reply_comments")
index = 2
'''
资讯页
'''
for i in range(len(url_list)): # 循环链接列表中有多少个链接循环多少次
print(i)
url = url_list[i]
res = requests.get(url, headers=headers2, timeout=100) # 返回链接
res.encoding = res.apparent_encoding # apparent_encoding会从网页的内容中分析网页编码的方式
html = res.text # 网页代码含有汉字的地方可以直接输出汉字
soup = BeautifulSoup(html, "html.parser") # 指定解析html的解析器为"html.parser",可以把网络中标签值提取出来
sleep(random.uniform(1,3))
read_list = soup.select(".l1.a1")[1:] # [1:]从网页源代码中的第一个.l1.a1开始取;若不加[1:]则爬取的内容包含"阅读"
comment_list = soup.select(".l2.a2")[1:]
title_list = soup.select(".l3.a3")[1:]
author_list = soup.select(".l4.a4")[1:]
renew_list = soup.select(".l5.a5")[1:]
'''
正文页
'''
for k in range(len(title_list)): # title_list中有几个元素循环多少次
outws.cell(row=index, column=1, value=str(read_list[k].text.strip())) # 剥离字符串 写在第二行
# print(str(read_list[k].text.strip()))
outws.cell(row=index, column=2, value=str(comment_list[k].text.strip()))
outws.cell(row=index, column=3, value=str(title_list[k].select('a')[0]["title"]))
'''
找到a所含的内容(输出为列表)[0]:取出第一个元素(此列表中只有一个元素);['title']:因为有title=,故可以返回后面的值
'''
outws.cell(row=index, column=4, value=str(author_list[k].text.strip()))
outws.cell(row=index, column=5, value=str(renew_list[k].text.strip()))
outws.cell(row=index, column=6, value='https://guba.eastmoney.com'+str(title_list[k].select('a')[0]["href"])) # 找到a中的herf
"""
获得正文链接里的资讯正文
"""
url1 = "http://guba.eastmoney.com" + str(title_list[k].select('a')[0]["href"]) # 获得正文对应链接
res1 = requests.get(url1, headers=headers2,timeout=100) # 返回链接
data = etree.HTML(res1.text) # etree.HTML方法把html的文本内容解析成html对象,并对HTML文本进行自动修正
source = data.xpath(
'//div[contains(@id,"zw_header")]//span[@class="source"]//text()') # 判断div标签中的div是否包含zw_header;//代表所有的子节点
str1 = str(source)
source1 = str1[5:-2]
outws.cell(row=index, column=7, value=source1)
body = data.xpath('//div[contains(@id,"zw_body")]//p//text()')
str2 = str(body)
body1 = str2[1:-1]
body2 = body1.replace("'", "")
body3 = body2.replace("u3000", "")
body4 = body3.replace("\\", "")
body4=ILLEGAL_CHARACTERS_RE.sub(r'',body4)
# print(body4)
b1, b2, b3 = body4.partition(", .autoimg")
outws.cell(row=index, column=8, value=body4)
二、动态传输
此部分主要涉及新闻评论等相关内容的提取,因为评论同弹幕类似,均属于动态内容,甚至随时更新,故爬取时同前面的基本信息爬取有些区别,也是困扰我许久的地方,最终借助了神秘的第三方力量得以解决
其中用到了抓 包技术,大家可以自行搜索更详细的教程
值得注意的是,本文仅爬取了对于新闻的评论,对于评论的评论并没有爬取
'''
article_reply
'''
url2 = 'http://guba.eastmoney.com/interface/GetData.aspx' # 全部东方财富股吧动态传输均适用,更改网站可以重新抓包,找到。aspx文件的url
'''
"请求"中有很多信息,如若把握不准则全部粘贴进来
referer无影响,可以设定任何值
'''
headers2 = {
'Referer': '1',
'User-Agent': 'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/96.0.4664.110Safari/537.36' # 此条也可以没有,只保留referer也可运行
}
postid = str(title_list[k].select('a')[0]["href"])[-14:-5] # 每条资讯正文链接里的特定代码,并非股票代码
data1 = {
'param': f'postid={postid}&sort=1&sorttype=1&p=1000000&ps=50', # p=任意值,返回的['count']均为对于该文章评论数
'path': 'reply/api/Reply/ArticleNewReplyList',
'env': '2'
}
res2 = requests.post(url=url2, headers=headers2, data=data1,timeout=100).json()
a_r_c = res2['count'] # 获取评论文章数
pages2 = math.ceil(a_r_c / 50) # 向上取整获取翻页最小值
outws.cell(row=index, column=9, value=a_r_c) # 写入arc
for p in range(pages2): # 循环总页数
data2 = {
'param': f'postid={postid}&sort=1&sorttype=1&p={p+1}&ps=50', # p从0开始,故为p+1
'path': 'reply/api/Reply/ArticleNewReplyList',
'env': '2'
}
res3 = requests.post(url=url2, headers=headers2, data=data2, timeout=100).json()
index2 = 10+50*p # 每页50条评论,写完第一页后,第二页要从第60列开写如excel
for li1 in res3['re']: # 循环每页中的每条re(字典)
com1 = li1['reply_text'] # 获取re中的每个reply_text(字典)
com1=ILLEGAL_CHARACTERS_RE.sub(r'',com1)
outws.cell(row=index, column=index2, value=com1) # 每条评论写入excel
index2 += 1 # 自动换列写入excel
index += 1 # 自动换行写入excel
sleep(random.uniform(1,4))
outwb.save("资讯mt9.xlsx")
#outputData.to_excel(outputExcelFilePath, engine='xlsxwriter')
if __name__ == "__main__":
pages1 = 44
url_list = get_url(pages1)
get_news(url_list)
print("运行完成")
注意
如若我们一次性爬取较多页数,会激活网站反pa机制,以至于无法访问网页;
可以试一下多线程或多进程
更多推荐
所有评论(0)