Python爬取糗事百科示例代码
2024-10-20 18:52:41
参考链接:http://python.jobbole.com/81351/#comment-93968
主要参考自伯乐在线的内容,但是该链接博客下的源码部分的正则表达式部分应该是有问题,试了好几次,没试成功。后来在下面的评论中看到有个使用BeautifulSoup的童鞋,试了试,感觉BeautifulSoup用起来确实很便捷。
# -*- coding:utf-8 -*- '''
Author:LeonWen
''' import urllib
import urllib2
# import re
from bs4 import BeautifulSoup page = 1
url = 'http://www.qiushibaike.com/hot/page/' + str(page)
# set the headers
user_agent = 'Mozilla/4.0(compatible;MSIE 5.5;Windows NT)'
headers = {'User-Agent':user_agent}
try:
request = urllib2.Request(url,headers=headers)
response = urllib2.urlopen(request)
object_bs = BeautifulSoup(response.read())
# print object_bs.prettify()
# items 是一个list保存着返回结果
items = object_bs.body.find_all("div",{"class":"article block untagged mb15"})
# print items
floor = 1
tag = 0
for item in items:
if item.find("div",{"class":"thumb"}) == None:
# class=thumb为带有图片的标签
author = item.find("h2")
upNum = item.find("i",{"class":"number"})
content = item.find("div",{"class":"content"})
# print content.prettify()
# print content.text
print u"===============",floor,u" 楼 ======================="
print u"作者:",author.text
print u"赞同数:",upNum.text
print u"内容:",content.get_text()
floor += 1
else:
tag += 1
print u"图片个数:",tag
except urllib2.URLError,e:
if hasattr(e,"code"):
print e.code
if hasattr(e,"reason"):
print e.reason
原文地址:http://www.cnblogs.com/leonwen/p/5721843.html
最新文章
- en_windows_10_multiple_editions_version_1511_x64.iso
- [异常解决] 初玩SAE遇到的小问题——注册&;创建项目+MyEclipse装插件直接部署+一个简单的JSP部署实现
- Centos7 Apache 2.4.18编译安装
- scrollTop 鼠标往下移动到一定位置显示隐藏
- ECharts SSH+JQueryAjax+Json+JSP将数据库中数据填充到ECharts中
- C - Courses - hdu 1083(模板)
- HDU_2057——64位无符号16进制数的运算
- css 实现评分效果
- As Easy As A+B
- (hdu step 7.1.2)You can Solve a Geometry Problem too(乞讨n条线段,相交两者之间的段数)
- wemall app商城源码android开发MD5加密工具类
- ES6之Promise
- java.sql.SQLException:ORA-01861:文字和格式字符串不匹配
- 城市经纬度 json
- python小程序--Two
- 获取上一页面url
- Ajax接收后台发送过来的布尔值以及指定的字符串
- socket.io的connect连接时不断的进行自动连接,并产生错误net::ERR_EMPTY_RESPONSE
- spring 注解@PathVariable
- 尚硅谷STRUTS2视频学习笔记