网络爬虫入门:你的第一个爬虫项目(requests库)

0.采用requests库

虽然urllib库应用也很广泛,而且作为Python自带的库无需安装,但是大部分的现在python爬虫都应用requests库来处理复杂的http请求。requests库语法上简洁明了,使用上简单易懂,而且正逐步成为大多数网络爬取的标准。

1. requests库的安装
采用pip安装方式,在cmd界面输入:

pip install requests

小编推荐一个学python的学习qun 491308659 验证码:南烛
无论你是大牛还是小白,是想转行还是想入行都可以来了解一起进步一起学习!裙内有开发工具,很多干货和技术资料分享

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>
上一篇:String literal is not properly closed by a double-quote eclipse


下一篇:SpringMVC配置字符过滤器的两种方式