首先进入到 http://www.budejie.com/text/,里面所有是段子,暂时只把段子爬下来,不爬图片,打开页面查看源代码:html
发现段子都在相似于这样 <a href="(/detail-3242432.html)">段子</a>
的结构中,
因而咱们有办法了,把段子在的地方放入正则表达式reg = re.compile(r'<a href="(/detail-.*?)">(.*?)</a>')
点赞的人数也是重复上面的过程:python
正则表达式reg = re.compile(r'<i class="icon-up ui-icon-up"></i> <span>(.*?)</span>
正则表达式
代码以下:markdown
# encoding: utf-8
import urllib2
import re
def getduan():
url = 'http://www.budejie.com/text/'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'#代理
headers = {'User-Agent': user_agent}
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
res = response.read()
reg = re.compile(r'<a href="(/detail-.*?)">(.*?)</a>')
return re.findall(reg, res)
def up():
url = 'http://www.budejie.com/text/'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
res = response.read()
reg = re.compile(r'<i class="icon-up ui-icon-up"></i> <span>(.*?)</span>')
return re.findall(reg, res)
if __name__ == '__main__':
d = zip(getduan(), up())
d = dict(d)
count = 0
for j, i in d.items():
print '段子', (count+1),j[1]
count = count+1
print 'up人数:',i
这里用到了代理,为了防止反爬虫,环境是python2.7,最后获得的效果如图:框架
很是简单的爬虫没有用任何框架,接下来会用框架解决爬虫问题,请继续关注。python2.7