一、随时随地爬取一个网页下来

  怎么爬取网页?对网站开发了解的都知道,浏览器访问Url向服务器发送请求,服务器响应浏览器请求并返回一堆HTML信息,其中包括html标签,css样式,js脚本等。我们之前用的是Python标准基础库Urllib实现的,

现在我们使用Python的Requests HTTP库写个脚本开始爬取网页。Requests的口号很响亮“让HTTP服务人类“,够霸气。

二、Python Requests库的基本使用

1.GET和POST请求方式

GET请求

 import requests

 payload = {"t": "b", "w": "Python urllib"}
response = requests.get('http://zzk.cnblogs.com/s', params=payload)
# print(response.url) # 打印 http://zzk.cnblogs.com/s?w=Python+urllib&t=b&AspxAutoDetectCookieSupport=1
print(response.text)

Python requests的GET请求,不需要在作为请求参数前,对dict参数进行urlencode()和手动拼接到请求url后面,get()方法会直接对params参数这样做。

POST请求

 import requests

 payload = {"t": "b", "w": "Python urllib"}
response = requests.post('http://zzk.cnblogs.com/s', data=payload)
print(response.text) # u'......'

Python requests的POST请求,不需要在作为请求参数前,对dict参数进行urlencode()和encode()将字符串转换成字节码。raw属性返回的是字节码,text属性直接返回unicode格式的字符串,而不需要再进行decode()将返回的bytes字节码转化为unicode。

相对于Python urllib而言,Python requests更加简单易用。

 2.设置请求头headers

 import requests

 payload = {"t": "b", "w": "Python urllib"}
headers = {'user_agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get('http://zzk.cnblogs.com/s', params=payload, headers=headers)
print(response.request.headers)

get方法的请求头,可以通过传递字典格式的参数给headers来实现。response.headers返回服务器响应的请求头信息,response.request.headers返回客户端的请求头信息。

3.设置会话cookie

 import requests

 cookies = {'cookies_are': 'working'}
response = requests.get('http://zzk.cnblogs.com/', cookies=cookies)
print(response.text)

requests.get()方法cookies参数除了支持dict()字典格式,还支持传递一个复杂的RequestsCookieJar对象,可以指定域名和路径属性。

 import requests
import requests.cookies cookieJar = requests.cookies.RequestsCookieJar()
cookieJar.set('cookies_are', 'working', domain='cnblogs', path='/cookies')
response = requests.get('http://zzk.cnblogs.com/', cookies=cookieJar)
print(response.text)

4.设置超时时间timeout

 import requests

 response = requests.get('http://zzk.cnblogs.com/', timeout=0.001)
print(response.text)

三、Python Requests库的高级使用

1.Session Object

 from requests import Request,Session

 s = Session()

 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('http://httpbin.org/cookies') print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'

通过Session,我们可以在多个请求之间传递cookies信息,不过仅限于同一域名下,否则不会附带上cookie。如果碰到需要登录态的页面,我们可以在登陆的时候保存登录态,再访问其他页面时附带上就好。

2.Prepared Requested

 from requests import Request,Session

 url = 'http://zzk.cnblogs.com/s'
payload = {"t": "b", "w": "Python urllib"}
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Content-Type':'application/x-www-form-urlencoded'
}
s = Session()
request = Request('GET', url, headers=headers, data=payload)
prepped = request.prepare() # do something with prepped.headers
del prepped.headers['Content-Type']
response = s.send(prepped, timeout=3)
print(response.request.headers)

Request对象的prepare()方法返回的对象允许在发送请求前做些额外的工作,例如更新请求体body或者请求头headers.

3.Set Proxy

 import requests

 # set headers
user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4'
headers = {'User-Agent': user_agent}
url = 'http://passport.xxx.com/auth/valid.json'
proxies = {'http': 'http://10.1.1.1:80'} # set http proxy
params = {'uin': 'xxxxxx', 'passwd': 'xxxxxx', 'imgcode': 'ijyk', '_1': '',
'_2': '', '_3': '', 'url': ''} response = requests.post(url, headers=headers, data=params, proxies=proxies)
response.raise_for_status()
if response.status_code == requests.codes.ok:
print(response.text)

requests.get()和post()方法均支持http proxy代理,只要传递proxies = {'http': 'http://10.1.1.1:80'}字典对象,可以实现把请求传递给代理服务器,代理服务器从10.1.1.1:80取回响应数据返回来。

四、Python Requests库的实际应用

 1.GET请求封装

 def do_get_request(self, url, headers=None, timeout=3, is_return_text=True, num_retries=2):
if url is None:
return None
print('Downloading:', url)
if headers is None: # 默认请求头
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = None
try:
response = requests.get(url,headers=headers,timeout=timeout) response.raise_for_status() # a 4XX client error or 5XX server error response,raise requests.exceptions.HTTPError
if response.status_code == requests.codes.ok:
if is_return_text:
html = response.text
else:
html = response.json()
else:
html = None
except requests.Timeout as err:
print('Downloading Timeout:', err.args)
html = None
except requests.HTTPError as err:
print('Downloading HTTP Error,msg:{0}'.format(err.args))
html = None
if num_retries > 0:
if 500 <= response.status_code < 600:
return self.do_get_request(url, headers=headers, num_retries=num_retries - 1) # 服务器错误,导致请求失败,默认重试2次
except requests.ConnectionError as err:
print('Downloading Connection Error:', err.args)
html = None return html

2.POST请求封装

  def do_post_request(self, url, data=None, headers=None, timeout=3, is_return_text=True, num_retries=2):
if url is None:
return None
print('Downloading:', url)
# 如果请求数据未空,直接返回
if data is None:
return
if headers is None:
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = None
try:
response = requests.post(url,data=data, headers=headers, timeout=timeout) # 设置headers timeout无效 response.raise_for_status() # a 4XX client error or 5XX server error response,raise requests.exceptions.HTTPError
if response.status_code == requests.codes.ok:
if is_return_text:
html = response.text
else:
html = response.json()
else:
print('else')
html = None
except requests.Timeout as err:
print('Downloading Timeout:', err.args)
html = None
except requests.HTTPError as err:
print('Downloading HTTP Error,msg:{0}'.format(err.args))
html = None,
if num_retries > 0:
if 500 <= response.status_code < 600:
return self.do_post_request(url, data=data, headers=headers,
num_retries=num_retries - 1) # 服务器错误,导致请求失败,默认重试2次
except requests.ConnectionError as err:
print('Downloading Connection Error:', err.args)
html = None return html

3.登录态cookie

 def save_cookies(self, requeste_cookiejar, filename):
with open(filename, 'wb')as f:
pickle.dump(requeste_cookiejar, f) def load_cookies(self, filename):
with open(filename, 'rb') as f:
return pickle.load(f) # save request cookies
r = requests.get(url)
save_cookies(r.cookies,filename) # load cookies and do a request
requests.get(url,cookies=load_cookies(filename))

Python爬虫基础之requests的更多相关文章

  1. Python爬虫基础

    前言 Python非常适合用来开发网页爬虫,理由如下: 1.抓取网页本身的接口 相比与其他静态编程语言,如java,c#,c++,python抓取网页文档的接口更简洁:相比其他动态脚本语言,如perl ...

  2. python爬虫-基础入门-python爬虫突破封锁

    python爬虫-基础入门-python爬虫突破封锁 >> 相关概念 >> request概念:是从客户端向服务器发出请求,包括用户提交的信息及客户端的一些信息.客户端可通过H ...

  3. python爬虫-基础入门-爬取整个网站《3》

    python爬虫-基础入门-爬取整个网站<3> 描述: 前两章粗略的讲述了python2.python3爬取整个网站,这章节简单的记录一下python2.python3的区别 python ...

  4. python爬虫-基础入门-爬取整个网站《2》

    python爬虫-基础入门-爬取整个网站<2> 描述: 开场白已在<python爬虫-基础入门-爬取整个网站<1>>中描述过了,这里不在描述,只附上 python3 ...

  5. python爬虫-基础入门-爬取整个网站《1》

    python爬虫-基础入门-爬取整个网站<1> 描述: 使用环境:python2.7.15 ,开发工具:pycharm,现爬取一个网站页面(http://www.baidu.com)所有数 ...

  6. python爬虫之一:requests库

    目录 安装requtests requests库的连接异常 HTTP协议 HTTP协议对资源的操作 requests库的7个主要方法 request方法 get方法 网络爬虫引发的问题 robots协 ...

  7. Python爬虫基础(一)——HTTP

    前言 因特网联系的是世界各地的计算机(通过电缆),万维网联系的是网上的各种各样资源(通过超文本链接),如静态的HTML文件,动态的软件程序······.由于万维网的存在,处于因特网中的每台计算机可以很 ...

  8. 【学习笔记】第二章 python安全编程基础---python爬虫基础(urllib)

    一.爬虫基础 1.爬虫概念 网络爬虫(又称为网页蜘蛛),是一种按照一定的规则,自动地抓取万维网信息的程序或脚本.用爬虫最大的好出是批量且自动化得获取和处理信息.对于宏观或微观的情况都可以多一个侧面去了 ...

  9. python爬虫基础要学什么,有哪些适合新手的书籍与教程?

    一,爬虫基础: 首先我们应该了解爬虫是个什么东西,而不是直接去学习带有代码的内容,新手小白应该花一个小时去了解爬虫是什么,再去学习带有代码的知识,这样所带来的收获是一定比你直接去学习代码内容要多很多很 ...

随机推荐

  1. Web APP & 弹窗插件

    Web APP & 弹窗插件 移动端弹窗插件 alert.confirm.toast.notice 四种类型弹窗 jQuery & Zepto https://github.com/s ...

  2. MySQL数据库存储引擎

    这里主要介绍最常用的两种存储引擎. 1.InnoDB InnoDB是一个事务型的存储引擎,有行级锁定和外键约束.Innodb引擎提供了对数据库ACID事务的支持,并且实现了SQL标准的四种隔离级别,关 ...

  3. MDS

    转载:https://blog.csdn.net/victoriaw/article/details/78500894 多维缩放(Multidimensional Scaling, MDS)是一组对象 ...

  4. UNION的使用方法 (表与表直接数据和在一起的示例)

    SELECT o.CATEGORY CATEGORY,o.KEY_WORK KEY_WORK FROM BO_EU_KEY_WORK wo RIGHT OUTER JOIN BO_EU_WORK_ON ...

  5. Luogu4491 [HAOI2018]染色 【容斥原理】【NTT】

    题目分析: 一开始以为是直接用指数型生成函数,后来发现复杂度不对,想了一下容斥的方法. 对于有$i$种颜色恰好出现$s$次的情况,利用容斥原理得到方案数为 $$\binom{m}{i}\frac{P_ ...

  6. Linux keepalived+nginx实现主从模式

    双机高可用方法目前分为两种: 主从模式:一台主服务器和一台从服务器,当配置了虚拟vip的主服务器发送故障时,从服务器将自动接管虚拟ip,服务将不会中断.但主服务器不出现故障的时候,从服务器永远处于浪费 ...

  7. H3C WAP712C 路由器设置

    0.做完任何设置之后都要执行保存操作,否则断电后设置会丢失! 1.默认登录参数:IP:192.168.0.50ID:adminPD:h3capadmin 2.修改默认IP地址:设备 --> 接口 ...

  8. k8s list

    https://mp.weixin.qq.com/s?__biz=MzI5ODQ2MzI3NQ==&mid=2247486341&idx=1&sn=53b0c92deb0cb8 ...

  9. (String) leetcode 67. Add Binary

    Given two binary strings, return their sum (also a binary string). The input strings are both non-em ...

  10. 分类器的评价指标-ROC&AUC

    ROC 曲线:接收者操作特征曲线(receiver operating characteristic curve),是反映敏感性和特异性连续变量的综合指标,roc 曲线上每个点反映着对同一信号刺激的感 ...