Python网络爬虫-你的第一个爬虫(requests库)
2018-03-07 22:43
489 查看
0.采用requests库
虽然urllib库应用也很广泛,而且作为Python自带的库无需安装,但是大部分的现在python爬虫都应用requests库来处理复杂的http请求。requests库语法上简洁明了,使用上简单易懂,而且正逐步成为大多数网络爬取的标准。1. requests库的安装
采用pip安装方式,在cmd界面输入:pip install requests
requests 官方文档http://python-requests.org。
2. 示例代码
我们将处理http请求的头部处理来简单进行反反爬虫处理,以及代理的参数设置,异常处理等。import requests def download(url, num_retries=2, user_agent='wswp', proxies=None): '''下载一个指定的URL并返回网页内容 参数: url(str): URL 关键字参数: user_agent(str):用户代理(默认值:wswp) proxies(dict): 代理(字典): 键:‘http’'https' 值:字符串(‘http(s)://IP’) num_retries(int):如果有5xx错误就重试(默认:2) #5xx服务器错误,表示服务器无法完成明显有效的请求。 #https://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81 ''' print('==========================================') print('Downloading:', url) headers = {'User-Agent': user_agent} #头部设置,默认头部有时候会被网页反扒而出错 try: resp = requests.get(url, headers=headers, proxies=proxies) #简单粗暴,.get(url) html = resp.text #获取网页内容,字符串形式 if resp.status_code >= 400: #异常处理,4xx客户端错误 返回None print('Download error:', resp.text) html = None if num_retries and 500 <= resp.status_code < 600: # 5类错误 return download(url, num_retries - 1)#如果有服务器错误就重试两次 except requests.exceptions.RequestException as e: #其他错误,正常报错 print('Download error:', e) html = None return html #返回html print(download('http://www.baidu.com'))
结果:
Downloading: http://www.baidu.com <!DOCTYPE html> <!--STATUS OK--> ... </script> <script> if(navigator.cookieEnabled){ document.cookie="NOJS=;expires=Sat, 01 Jan 2000 00:00:00 GMT"; } </script> </body> </html>
相关文章推荐
- python网络爬虫(二)编写第一个爬虫
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- 我的第一个Python3 网络爬虫 百度百科爬虫
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- 用python编写第一个简易爬虫(Requests库、BeatifulSoup、正则表达式入门)
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- Python网络爬虫——我的第一个爬虫(爬取郑州未来一周天气预报)
- python 网络爬虫入门(一)———第一个python爬虫实例
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- python 网络爬虫入门(1)———第一个python爬虫实例
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- Python 3: 第一个网络爬虫:下载网页—指定内容
- python爬虫---Requests库的基本使用
- [Python]网络爬虫(六):一个简单的百度贴吧的小爬虫