码迷,mamicode.com
首页 > 编程语言 > 详细

python3爬虫学习笔记

时间:2017-12-29 18:59:28      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:request   head   user   span   tps   请求头   修改   code   浏览器   

Robot.txt

Robots协议(也称为爬虫协议、机器人协议等)的全称是“网络爬虫排除标准”(Robots Exclusion Protocol),网站通过Robots协议告诉搜索引擎哪些页面可以抓取,哪些页面不能抓取。查看百度的robots协议www.baidu.com/robots.txt

一个简单的爬虫程序

  >>> import urllib.request
  >>> response = urllib.request.urlopen("https://www.baidu.com")  #打开url
  >>> data = response.read().decode(‘utf-8‘)    #读取百度html内容
  >>> print(data)    #打印读取到的html

写内容到本地

>>>filename = urllib.request.urlretrieve("http://edu.51cto.com",filename="D:/2.html")

使用urlretrieve会产出缓存,可以用urlcleanup()清除

>>>urllib.request.urlcleanup()

一般的url标准只允许一部分ASCLL字符,对于不合法的字符(中文,:等)需要编码,使用quote()编码unquote()解码

>>>urllib.request.quote(‘http://www.sina.com‘)
    ‘http%3A//www.sina.com‘
>>>urllib.request.unquote(‘http%3A//www.sina.com‘)
   http://www.sina.com

浏览器模拟--headers属性

很多网站都有反爬虫,这时我们需要模拟浏览器,需要设置User-Agent信息,可以通过在浏览器打开开发者模式在network中查看http请求查找User-Agent信息

方法1:使用build_opener()

>>> url = ‘http://www.baidu.com‘
>>> headers = (‘User-Agent‘,
           ‘ Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) ‘
           ‘AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36‘)
>>> opener = urllib.request.build_opener()
>>> opener.addheaders = [headers]
>>> data = opener.open(url).read().decode(‘utf-8‘)

方法2:使用add_header()添加报头

使用urllib.request.Request()的add_header()方法,urllib.request.Request()是用来生成请求的,可以修改各种请求头信息

>>> url = ‘http://www.baidu.com‘
>>> req = urllib.request.Request(url)
>>> req.add_header(‘.....‘)
>>> data = urllib.request.urlopen(req).read().decode(‘utf-8‘)

设置超时

urllib.request.urlopen(‘url‘,time_out=?)

>>> try:
>>>     for i in range(2):
>>>         urllib.request.urlopen(‘url‘,timeout=3).read().decode(‘utf-8‘)
>>> except Exception as e:
>>>     print(e)

python3爬虫学习笔记

标签:request   head   user   span   tps   请求头   修改   code   浏览器   

原文地址:https://www.cnblogs.com/luoyuGG/p/8145065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!