爬虫实战--抓取糗事百科前10页数据
来源:互联网 发布:甘肃广播电视网络官网 编辑:程序博客网 时间:2024/06/05 19:38
1.使用三个库:urllib2, re , lxml ,自行百度安装,
# -*- coding:utf-8 -*-import urllib2import reimport lxml.html as htmldef get_url(url): #封装一次url的请求,获得3个参数 User_Agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36' header = { 'User-Agent':User_Agent } #不使用headers传参数將无法获取到页面数据 try: req = urllib2.Request(url,headers=header) response = urllib2.urlopen(req) content = response.read().decode('utf-8') # print content tree = html.fromstring(content) #将源码进行转化,这样就可以通过tree来使用xpath, aa = tree.xpath('//*[@id="content-left"]//div[@class="article block untagged mb15"]') wenben = tree.xpath('//text()') wenben = "".join(wenben).strip() #获取当前页面中文本, meiyetiaoshu = len(aa)#获取当前页面中有几条数据 return tree, meiyetiaoshu, wenben, except urllib2.URLError, e: if hasattr(e, 'code'): print e.code if hasattr(e, 'reason'): print e.reason#抓取每一页中的所有条数数据def page_one(tree,wenben,meiyetiaoshu): for i in range(1,meiyetiaoshu+1): zuozhe = tree.xpath('//*[@id="content-left"]//div[{}]/div[1]/a[2]/@title'.format(i)) if not zuozhe: #对匿名用户的处理, zuozhe = tree.xpath('//*[@id="content-left"]//div[{}]/div[1]/span[2]/h2/text()'.format(i)) print i,zuozhe[0] #获取得到用户名称, duanzi = tree.xpath('//*[@id="content-left"]//div[{}]/a/div/span/text()'.format(i)) print duanzi[0].strip() #获取得到用户说的笑话信息, sub_zuozhe= re.sub(u'(\*|\(|\)|\~|\^)','',zuozhe[0]) #里面有特殊字符,将其中的特殊字符替换掉 wenben = re.sub(u'(\*|\(|\)|\~|\^)','',wenben) #将文本中的特殊字符页替换掉, haoxiao_group = re.search(u'%s[\d\D]+?(\d+ 好笑)'%sub_zuozhe,wenben) print haoxiao_group.group(1).strip() 获取得到里面有多少人觉得好笑,评论数也可以用相同的方法抓取#抓取前10页数据,for page in range(1,11): url = 'http://www.qiushibaike.com/hot/page/%s/'%str(page) #前10页的url tree, meiyetiaoshu, wenben = get_url(url) page_one(tree=tree,wenben=wenben,meiyetiaoshu=meiyetiaoshu)
0 0
- 爬虫实战--抓取糗事百科前10页数据
- 实战抓取糗事百科
- 爬虫实战--糗事百科
- Python爬虫实战:糗事百科
- ruby+nokogori抓取糗事百科前10頁並存儲進資料庫示例
- Python网络爬虫抓取糗事百科
- Python 爬虫实战 - 糗事百科段子
- Python爬虫实战之爬糗事百科
- python3爬虫(二)实战- 爬糗事百科
- Scrapy爬虫实战四:糗事百科
- [python爬虫] 抓取糗事百科的爬虫程序
- Python爬虫实例2-多线程爬虫抓取糗事百科数据
- Python 爬虫 —— 糗事百科爬虫实战
- Python3.4简单爬虫实现之抓取糗事百科段子
- Python3 定向爬虫之“抓取糗事百科图片”
- Python网络爬虫(5)糗事百科段子抓取
- Python3抓取糗事百科
- Python抓取糗事百科
- java访问数据库
- 11 个 Android Studio 的好用插件
- C++抽象编程——STL(5)——剔除重复元素
- linux的基本语法及一些设置
- 表格中的iframe实现打开多个网页
- 爬虫实战--抓取糗事百科前10页数据
- 链表的按条件删除
- JSON数据解析
- java中import导入自定义包
- SQLite Expert Professional 3查看SQLite数据
- tensorflow分类预测引发的性能测试
- 如何在angularjs里面选择一个按钮而不改变其他按钮的颜色
- 设计模式
- web网站无埋点技术,分析数据。