Python网络爬虫(5)糗事百科段子抓取
来源:互联网 发布:二战日本兵力知乎 编辑:程序博客网 时间:2024/04/29 06:40
def get_html(url): try: html = urlopen(url) except HTTPError as e: print(e) return None except URLError as e: print(e) return None try: bsObj = BeautifulSoup(html,"html.parser") return bsObj except AttributeError as e: print(e) return None
这个打开煎蛋网的函数打不开糗事百科 因为有对爬虫的限制
让网络机器人看起来像人类用户
网站防采集的前提就是要正确地区分人类访问用户和网络机器人。虽然网站可以使用很多识别技术(比如验证码)来防止爬虫,但还是有一些十分简单的方法,可以让你的网络机器人看起来更像人类访
问用户。
修改请求头
在第 9 章里,我们曾经用 requests 模块处理网站的表单。requests 模块还是一个设置请求头的利器。HTTP 的请求头是在你每次向网络服务器发送请求时,传递的一组属性和配置信息。HTTP 定义
了十几种古怪的请求头类型,不过大多数都不常用。只有下面的七个字段被大多数浏览器用来初始化所有网络请求(表中信息是我自己浏览器的数据)。
属性内容
Host https://www.google.com/
Connection keep-alive
Accept text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Referrer https://www.google.com/
Accept-Encoding gzip,deflate,sdch
Accept-Language en-US,en;q=0.8
经典的 Python 爬虫在使用 urllib 标准库时,都会发送如下的请求头:
属性 内容
Accept-Encoding identity
User-Agent Python-urllib/3.4
如果你是一个防范爬虫的网站管理员,你会让哪个请求头访问你的网站呢?
Talk is cheap,show the code!
from urllib.request import urlopenfrom urllib.error import HTTPErrorfrom urllib.error import URLErrorfrom bs4 import BeautifulSoupimport urllib.requestimport reimport osimport requestsdef get_html(url): session = requests.Session() headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)AppleWebKit 537.36 (KHTML, like Gecko) Chrome","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"} req = session.get(url, headers=headers) bsObj = BeautifulSoup(req.text,"html.parser") return bsObjdef get_msg(bsObj): for each in bsObj.findAll("div",{"class":"content"}): print(each.span.get_text())if __name__ == "__main__": html = get_html("http://www.qiushibaike.com/8hr/page/2/?s=4946249") get_msg(html)
OK 可以打开显示了
- Python网络爬虫(5)糗事百科段子抓取
- Python网络爬虫抓取糗事百科
- Python - 静态页面抓取(抓取‘糗事百科’段子)
- python抓取糗事百科的段子
- Python实现抓取糗事百科的段子
- python抓取糗事百科段子 图片
- 【网络爬虫】爬取糗事百科段子
- Python爬虫实战(1):爬取糗事百科段子
- Python爬虫实战(1):爬取糗事百科段子
- python 爬虫 爬取糗事百科段子
- Python 爬虫实战 - 糗事百科段子
- Python爬虫 爬取糗事百科段子
- python爬虫-糗事百科段子内容
- Python爬虫爬取糗事百科段子
- Python爬虫 爬取糗事百科段子
- 爬虫-糗事百科段子
- Python3.4简单爬虫实现之抓取糗事百科段子
- Python网络爬虫(6)糗事百科图片抓取按主题名保存
- linux应用之_文件IO前世今生
- C程序设计语言- 指针与数组-4.2----字符指针与函数、指针数组以及指向指针的指针、指针数组的初始化
- 成员函数和友元函数完成一元运算符重载
- 第一篇博客
- apt-get proxy 设置
- Python网络爬虫(5)糗事百科段子抓取
- MBP用u盘装mac和win双系统
- 【Javascript】返回上一页 返回下一页
- Delphi XE中String、ANSIString、TBytes之间的转换
- 45个实用的JavaScript技巧和实践
- Apache之——多虚拟主机多站点配置的两种实现方案
- openssl生成证书命令详解
- PHP中使用eAccelerator
- Linux常用命令发布啦!