当前位置: 首页 > 后端技术 > Python

python爬虫爬取微博评论案例详解_1

时间:2023-03-26 16:27:12 Python

本文主要介绍python爬虫爬取微博评论。小伙伴们快来和小编一起学习吧。前几天,杨超越编程大赛火了一把。大家都在报名,我也是其中之一。在我们的项目中,我负责数据爬取,主要收集杨超越的每一条评论的相关信息。数据格式:{"name":评论者姓名,"comment_time":评论时间,"comment_info":评论内容,"comment_url":评论者主页}以上就是我们需要的信息。抓取前分析:以上是杨超越的微博首页,这是我们首先需要获取的内容。因为我们需要在这个首页等待这些微博详情页的链接,但是当我们向下刷新的时候,会发现微博的首页信息是通过ajax动态加载的。这张图就是我们向下刷新得到的新链接。这是我们需要获取的信息页面信息。接下来就是获取详情页的信息了。详情页包含评论的相关信息。通过向下刷新,我们还会发现相关的评论信息也是通过ajax加载的。OK,以上就是我们对整个过程的粗略概括。分析过程。具体操作过程:我们总理获取到首页后,会发现内容中包含了相关的反爬措施,获取到的源码中的信息中含有很多转义字符“”,以及相关的“<”和“>”"都是直接用html语言写的,这会给我们的页面解析带来一定的问题。我们可以使用replace方法直接把这些转义字符全部去掉,然后我们就可以对这个页面进行常规处理,同时我也尝试过使用其他的分析方法,但是遇到了很多问题,就不介绍了太多了。我们在获取每条微博的链接之后,还需要获取一个非常关键的值id,这个值有什么用,它的主要作用是在评论页的ajax页面的拼接地址中使用。接下来就是找出我们找到的两个ajaxurl的特征或者规则:当我们从这些ajax中找到规则时,不难发现爬虫就差不多完成了。让我在下面显示我的代码:注意:请在标题中添加您自己的cookie#--coding:utf-8--Created:2018/8/2618:33author:GuoLiimportrequestsimportjsonimporttimefromlxmlimportetreeimporthtmlimportrefrombs4importBeautifulSoupclassWeibospider:def__init__(self):#获取首页相关信息:self.start_url='https://weibo.com/u/5644764907?page=1&is_all=1'self.headers={"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","accept-encoding":"gzip,deflate,br","accept-language":"zh-CN,zh;q=0.9,en;q=0.8","cache-control":"max-age=0","cookie":使用你自己的本地cookie,"referer":"https://www.weibo.com/u/5644764907?topnav=1&wvr=6&topsug=1","upgrade-insecure-requests":"1","user-agent":"Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/72.0.3626.96Safari/537.36",}self.proxy={'HTTP':'HTTP://180.125.70.78:9999','HTTP':'HTTP//117.90.4.230:9999','HTTP':'HTTP://111.77.196.229:9999','HTTP':'HTTP://111.177.183.57:9999','HTTP':'HTTP://123.55.98.146:9999',}defparse_home_url(self,url):#处理解析首页的细节(不包括通过ajax获取的两个页面)res=requests.get(url,headers=self.headers)response=res.content.decode().replace("\\","")#every_url=re.compile('target="_blank"href="(/\d+/\w+\?from=\w+&wvr=6&mod=weibotime)"rel="externalnofollow"',re.S).findall(response)every_id=re.compile('name=(\d+)',re.S).findall(response)#获取二级页面需要的idhome_url=[]foridinevery_id:base_url='https://weibo.com/aj/v6/comment/big?ajwvr=6&id={}&from=singleWeiBo'url=base_url.format(id)home_url.append(url)returnhome_urldefparse_comment_info(self,url):#抓取直接评论的人相关信息(名称,信息,时间,info_url)res=requests.get(url,headers=self.headers)response=res.json()count=response['data']['count']html=etree.HTML(response['data']['html'])name=html.xpath("//div[@class='list_liS_line1clearfix']/div[@class='WB_faceW_fl']/a/img/@alt")#评论者姓名info=html.xpath("//div[@node-type='replywrap']/div[@class='WB_text']/text()")#评论信息info="".join(info).replace("","").split("\n")info.pop(0)comment_time=html.xpath("//div[@class='WB_fromS_txt2']/text()")#评论时间name_url=html.xpath("//div[@class='WB_faceW_fl']/a/@href")#评论者的urlname_url=["https:"+iforiinname_url]comment_info_list=[]foriinrange(len(name)):item={}item["name"]=name[i]#存储评论者的屏幕名称item["comment_info"]=info[i]#存储评论信息item["comment_time"]=comment_time[i]#存储评论时间item["comment_url"]=name_url[i]#存储评论者的相关主页comment_info_list.append(item)returncount,comment_info_listdefwrite_file(self,path_name,content_list):对于content_list中的内容:用open(path_name,"a",encoding="UTF-8")作为f:f.write(json.dumps(content,ensure_ascii=False))f.write("\n")defrun(self):start_url='https://weibo.com/u/5644764907?page={}&is_all=1'start_ajax_url1='https://weibo.com/p/aj/v6/mblog/mbloglist?ajwvr=6&domain=100406&is_all=1&page={0}&pagebar=0&pl_name=Pl_Official_MyProfileFeed__20&id=1004065644764907&script_uri=/u/5644764907&pre_page={0}'start_ajax_url2='https://p/weibombrlog=?ajwdomain/6weibo/100406&is_all=1&page={0}&pagebar=1&pl_name=Pl_Official_MyProfileFeed__20&id=1004065644764907&script_uri=/u/5644764907&pre_page={0}'foriinrange(12):#lfself_par_sestart_url.format(i+1))#获取每个页面的微博ajax_url1=self.parse_home_url(start_ajax_url1.format(i+1))#Ajax加载页面微博ajax_url2=self.parse_home_url(start_ajax_url2.format(i+1))#Ajax第二页加载微博all_url=home_url+ajax_url1+ajax_url2forjinrange(len(all_url)):print(all_url[j])path_name="{}微博相关评论.txt".format(i*45+j+1)all_count,comment_info_list=self.parse_comment_info(all_url[j])self.write_file(path_name,comment_info_list)fornuminrange(1,10000):ifnum*15