python爬虫学习教程:爬取内涵段子【附源码】

文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

爬取内涵段子:
#encoding=utf-8import urllib2import reclass neihanba():def spider(self):'''爬虫的主调度器'''isflow=True#判断是否进行下一页page=1while isflow:url="http://www.neihanpa.com/article/list_5_"+str(page)+".html"html=self.load(url)self.deal(html,page)panduan=raw_input("是否继续(y/n)!")if panduan=="y":isflow=Truepage+=1else:isflow=Falsedef load(self,url):'''针对url地址进行全部爬去:param url: url地址:return: 返回爬去的内容'''header = {"User-Agent": " Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36"}request = urllib2.Request(url, headers=header)response = urllib2.urlopen(request)html = response.read()return htmldef deal(self,html,page):'''对之前爬去的内容进行正则匹配,匹配出标题和正文内容:param html:之前爬去的内容:param page: 正在爬去的页码'''parrten=re.compile('<li class="piclist\d+">(.*?)</li>',re.S)titleList=parrten.findall(html)for title in titleList:parrten1=re.compile('<a href="/article/\d+.html" rel="external nofollow" >(.*)</a>')ti1=parrten1.findall(title)parrten2=re.compile('<div class="f18 mb20">(.*?)</div>',re.S)til2=parrten2.findall(title)for t in ti1:tr=t.replace("<b>","").replace("</b>","")self.writeData(tr,page)for t in til2:tr=t.replace("<p>","").replace("</p>","").replace("<br>","").replace("<br />","").replace("&ldquo","\"").replace("&rdquo","\"")self.writeData(tr,page)def writeData(self,context,page):'''将最终爬去的内容写入文件中:param context: 匹配好的内容:param page: 当前爬去的页码数'''fileName = "di" + str(page) + "yehtml.txt"with open(fileName, "a") as file:file.writelines(context + "\n")if __name__ == '__main__':n=neihanba()n.spider()
大家可以套用代码灵活使用哟~

搜索下方加老师微信
老师微信号:XTUOL1988【切记备注:学习Python】
领取Python web开发,Python爬虫,Python数据分析,人工智能等精品学习课程。带你从零基础系统性的学好Python!
*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权

评论
