python3爬虫学习笔记

Posted luoyugg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3爬虫学习笔记相关的知识,希望对你有一定的参考价值。

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爬虫学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

scrapy主动退出爬虫的代码片段(python3)

python3爬虫学习笔记

python3网络爬虫笔记

python爬虫学习笔记-M3U8流视频数据爬虫

手动爬虫之流程笔记1(python3)

《python3 网络爬虫开发实践》笔记