爬一爬糗事百科
来源:互联网 发布:软件测试员有前途吗 编辑:程序博客网 时间:2024/05/16 11:16
这段时间在学python爬虫,就先拿糗事百科下手,教程是学点击打开链接这个的,但是我学的时候,糗事百科改版了,所以之前的正则表达式就不能用了,要自己写。
思路还是一样,先用hearders跳过验证,然后用urllib2.Request()和urllib2.urlopen()来获取网页内容,最后用正则式提取所想要的内容。
我提取的是作者、内容、点赞数和评论数。
在这里特别说一下我觉得最麻烦的其实是正则匹配,.*?这个可以匹配任何字符,所以没有用的字符都可以交给它,同时,不要忘记后面跟一个特别的字符,不然会贪婪太多的字符。
# -*- coding: utf-8 -*-__author__ = 'XYlander'import urllibimport urllib2import reclass crawler(object): def requesturl(self): page = 1 url = 'http://www.qiushibaike.com/hot/page/'+str(page) #URL地址 user_agent = 'Mozilla/4.0 (compatible;MSIE 5.5;Windows NT)' headers = {'User-Agent' : user_agent} try : request = urllib2.Request(url,headers=headers) self._response = urllib2.urlopen(request) #print self._response.read() print 'get' except urllib2.URLError,e: if hasattr(e,"code"): print e.code if hasattr(e,"reason"): print e.reason def absruct(self): content = self._response.read().decode('utf-8') pattern = re.compile('<div class="author clearfix">\n<a.*?img.*?h2>(.*?)</h2>.*?</div>.*?<div class="content">.*?<span>(.*?)</span>.*?<div class="stats".*?i class="number">(.*?)</i>.*?i class="number">(.*?)</i>',re.S) items = re.findall(pattern,content) for item in items: #print 'the author is {0},the content is {1},the number of like is {2},the number of comment is {3}'.format(item[0].encode('utf-8'),item[1],item[2],item[3]) print 'the author is %s,the content is %s,the number of like is%s,the number of comment %s'%(item[0],item[1],item[2],item[3])if __name__ == '__main__': cr = crawler() cr.requesturl() cr.absruct()
0 0
- 爬一爬糗事百科
- 糗事百科
- 糗事百科
- 糗事百科
- 糗事百科
- 糗事百科
- 糗事百科1
- 糗事百科2
- 糗事百科爬虫
- 糗事百科爬虫
- Python3抓取糗事百科
- python爬虫糗事百科
- 实战抓取糗事百科
- Python抓取糗事百科
- 糗事百科DEMO
- 糗事百科爬虫改进
- UI_糗事百科页面
- 糗事百科交互式爬虫
- 监听EditText文字变化,TextWatcher详解
- 2012蓝桥杯预赛试题本科c++微生物增殖
- 洛谷 P3399 丝绸之路
- SQL注入--MySql
- access_token
- 爬一爬糗事百科
- Web前端面试指导(二十六):JSON 格式是什么?你了解吗?
- HTML5应用现状分析
- python中的sum函数
- Android ADB常用命令
- PHP生成随机密码的4种方法及性能对比
- 青头小白装mongoDB,pymongo,pycharm安装mongod插件
- 关于博客
- 关于python的乱码问题