您的位置:首页 > 理论基础 > 计算机网络

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐