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

  怎么爬取网页?对网站开发了解的都知道,浏览器访问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. 一入OI深似海 4 —— 纪念我最后一次PJ(中)

    不知道怎么回事,直到比赛前10分钟才放我们进考场. 考场在体育馆里面,很大很壮观. 我匆匆忙忙地找到位子,屁股还没坐热,被老师告知不能带水. what?! 于是我只好把水放在统一放私人物品的地方. 电 ...

  2. php函数 array_count_values

    (PHP 4, PHP 5, PHP 7) array_count_values — 统计数组中所有的值 array_count_values ( array $array ) : array arr ...

  3. Django3 Django 路由分发,反向解析,2.0版本的path

    urls配置像Django 所支撑网站的目录.它的本质是URL与要为该URL调用的视图函数之间的映射表:你就是以这种方式告诉Django,对于客户端发来的某个URL调用哪一段逻辑代码对应执行. 1.简 ...

  4. ionic3创建选项卡

    html页面 <ion-content padding> <ion-segment [(ngModel)]="tabs"> <ion-segment- ...

  5. 继收购Magento十个月,Adobe推出Commerce Cloud商务云服务

    去年 5 月,软件巨头 Adobe 以 16.8 亿美元的价格,受过了 Magento .在经历了十个月的业务整合后,该公司终于推出了全新的 Commerce Cloud 商务云服务.据悉,其本质上是 ...

  6. Oracle 给予访问其他用户包的权限

    grant execute on apps.SPM_CON_INVOICE_INF_PKG to diq; grant  DEBUG on apps.SPM_CON_INVOICE_INF_PKG t ...

  7. [USACO19FEB]Mowing Mischief

    题目大意: 给定平面上的一些点,求这些点的一个\(LIS\),并且还需要满足下列式子最小: \[ \sum_{i=1}^{n-1}(a[i+1].x-a[i].x)*(a[i+1].y-a[i].y) ...

  8. LeetCode--11_974_Subarray_Sums_Divisible_by_K

    题目链接:点击这里 public static int subarraysDivByK(int[] A, int K) { int ans = 0,sum = 0; int[] B = new int ...

  9. VO、DTO、DO、PO

    领域模型中的实体类可细分为4种类型:VO.DTO.DO.PO. PO(Persistent Object):持久化对象,表示持久层的数据结构(如数据库表): DO(Domain Object):领域对 ...

  10. 树莓派中QT实现I2C

    树莓派中QT实现I2C 在QT中实现 I2C 使用的驱动为 wiringPi 库的引入 LIBS += -lwiringPi LIBS += -lwiringPiDev 代码实现 widget.h 中 ...