本文主要介绍python爬虫爬取微博评论。小伙伴们一起来和小编一起学习数据格式:{"name":评论者姓名,"comment_time":评论时间,"comment_info":评论内容,"comment_url":评论者主页}以上是我们需要的信息.具体操作过程:我们总理获取到首页后,会发现内容中包含了相关的反爬措施,获取到的源码中的信息中含有很多转义字符“”,以及相关的“<”和“>”"都是直接用html语言写的,这会给我们的页面解析带来一定的问题。我们可以使用replace方法直接把这些转义字符全部去掉,然后我们就可以对这个页面进行常规处理,同时我也尝试过使用其他的分析方法,但是遇到了很多问题,就不介绍了太多了。当我们获取每条微博的链接时,Axitrader返利http://www.fx61.com/brokerlis...,我们还需要获取一个非常关键的值id,这个值有什么用,主要的作用是在评论页ajax页面的拼接地址上使用。接下来就是找出我们找到的两个ajaxurl的特征或者规则:当我们从这些ajax中找到规则时,不难发现爬虫就差不多完成了。让我在下面显示我的代码:注意:请在标题中添加您自己的cookie--编码:utf-8--创建时间:2018/8/2618:33作者:GuoLiimportrequestsimportjsonimporttimefromlxmlimportetreeimporthtmlimportrefrombs4importBeautifulSoupclassWeibospider:def__init__(self):获取首页相关信息:self.start_url='https://weibo.com/u/564476490...'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,像Gecko)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)#获取二级页面Requiredidhome_url=[]foridinevery_id:base_url='https://weibo.com/aj/v6/comme...{}&from=singleWeiBo'url=base_url.format(id)home_url.append(url)returnhome_urldefparse_comment_info(self,url):#爬取直接评论者的相关信息(name,info,time,info_url)res=requests.get(url,headers=self.headers)response=res.json()count=response'data'html=etree.HTML(response'data')name=html.xpath("//div[@class='list_liS_line1clearfix']/div[@class='WB_faceW_fl']/a/img/@alt")#评论者'snameinfo=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):forcontentincontent_list:withopen(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/564476490...{}&is_all=1'start_ajax_url1='https://weibo.com/p/aj/v6/mbl..{0}&pagebar=0&pl_name=Pl_Official_MyProfileFeed__20&id=1004065644764907&script_uri=/u/5644764907&pre_page={0}'start_ajax_url2='https://weibo.com/p/aj/v6/mbl...{0}&pagebar=1&pl_name=Pl_Official_MyProfileFeed__20&id=1004065644764907&script_uri=/u/5644764907&pre_page={0}'foriinrange(12):#微博有12个页面home_url=self.parse_home_url(start_url.format(i+1))#获取每个页面的微博ajax_url1=self.parse_home_url(start_ajax_url1.format(i+1))#Ajax加载该页面的微博pageajax_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
