赞
踩
这次的案例实现的过程跟某条的差不多,因为两个案例有很多共同之处,如果想爬取某条评论的,又找不到思路,希望可以通过这个案例给大家一点小小的启发。
我们需要爬取的就是图片箭头这些新闻数据,可以很清楚的看到这些数据都是在主页里面,也就是说,这是一个纯纯的html网页,我们只需要提取出该网页里面的新闻的标题和新闻的链接就可以了,我们点击进入到新闻页面去看一下,我们需要找到该新闻的评论信息的位置,如图:
我们需要提取的就是箭头所指的这些,评论作者,作者id,评论内容,评论地这些数据,我们进入到分析页面去具体看一下,
如图所示,可以看到,我们直接定位的是xhr选项下,找到包含这些数据的数据包,发现是一个json格式的数据,找到了数据的位置,下面看一下数据的链接是如何形成的
可以看到这个数据包链接是通过这几个参数形成的,通过分析,这几个参数里面,codeid是一个变化的参数,pageno这个是翻页的参数,其他的参数都是固定的参数,我们最主要的就是要找到这个codeid参数,
通过搜索我们可以发现这个codeid的参数就在该新闻页面的里面,我们要找到这个参数,就要在包含该新闻页面的html里面提取出来这个参数,然后携带这个参数请求包含评论数据的链接,来获取我们需要的评论数据,最后保存数据就可以了,知道了大概的思路,下面我们就来看一下代码吧:
import httpx
import parsel
import re
import json
import pandas as pd
def parse_url(url):
with httpx.Client(base_url=home_url) as s:
r = s.get(url, headers=headers)
return r.content.decode()
def get_news_datas(html_str):
html = parsel.Selector(html_str)
for item in html.css('.Review-item>li'):
yield {
'news_title': item.css('.module-title>a::text').get(),
'news_link': item.css('.module-title>a::attr(href)').get(),
}
def get_params(html_str2):
news_id = re.search('_DOC_ID="(\d+)";', html_str2).group(1)
params = {
"codeId": news_id,
"codeType": "1",
"pageNo": "1",
"order": "1",
"ff": "www",
}
return params
def parse_url2(url, params): r = httpx.get(url, headers=headers, params=params) return r.content.decode() def get_comment_datas(news_data, json_str): json_datas = json.loads(json_str) for json_data in json_datas['items']: yield { # 提取新闻标题 'news_title': news_data['news_title'], # 提取评论作者名字 'comment_user': json_data['user_nick'], # 提取评论作者id 'comment_user_id': json_data['user_id'], # 提取评论的内容 'comment_text': json_data['content'].replace('\n', "").replace('<br />', "").replace('<strong>',"").replace('</strong>', ""), # 提取评论作者的所在城市 'comment_user_where': json_data['location_text'], }
def save_datas(comment_list):
df = pd.DataFrame(comment_list)
df.to_csv('./comment_data.csv', index=False,encoding='utf-8-sig')
print('数据保存成功')
def main():
comment_list = []
html_str = parse_url(home_url)
news_datas = get_news_datas(html_str)
for news_data in news_datas:
html_str2 = parse_url(news_data['news_link'])
params = get_params(html_str2)
json_str = parse_url2(api_url, params)
comment_datas = get_comment_datas(news_data, json_str)
for comment_data in comment_datas:
comment_list.append(comment_data)
save_datas(comment_list)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。