爬虫第二讲:重要的requests库

Requests库

什么是Request库

Requests是用Python语言编写,基于urllib,采用Apache2 Licensed开源协议的HTTP库。它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求。一句话--Python实现的简单易用的HTTP库。

安装Requests

pip3 install requests

request详解

  • 实例引入
import requests
response = requests.get('https://www.baidu.com')
print(type(response)) #<class 'requests.models.Response'>
print(response.status_code) #200
print(type(response.text))#class'str'
print(response.text)#响应的内容,返回的页面html
print(response.cookies)#<RequestsCookieJar[<Cookie  BDORZ=27315 for .baidu.com/>]>

  • 各种请求方法
import requests
requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')
  • 请求
    1.基本用法
import requests
#response = requests.get('http://www.baidu.com')
response = requests.get('http://httpbin.org/get')
print(response.text)

2.带参数的get请求

import requests
response = requests.get("http://httpbin.org/get?name=xiexie&age=22")
print(response.text)

这个参数编写起来蛮复杂的,以下是更清楚的做法,使用带参数的requests.get方法

import requests
data = {
        'name':'xiexie',
        'age':89
        }
response = requests.get('http://httpbin.org/get',params=data)
print(response.text)

3.解析Json

import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
print(response.json())
print(type(response.json()))

这在ajax请求时比较常用
4.获取二进制数据

import requests
response = requests.get('https://github.com/favicon.ico')
print(type(response.text),type(response.content))
print(response.text)
print(response.content)

response.text是string类型,而response.content是二进制流
保存二进制流到本地,图片、视频、音频都可以

import requests
response = requests.get('http://github.com/favicon.ico')
with open('favicon.ico','wb') as f:
    f.write(response.content)
    f.close()

5.添加headers作为爬虫来说,headers非常重要,演戏演全套。不然会被服务器识别出来被禁用。

import requests
response = requests.get('https://www.zhihu.com/explore')
print(response.text)

不用headers,直接返回400 Bad Request ,无法爬取,以下代码添加headers就能爬取了

import requests
headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
        }
response = requests.get('https://www.zhihu.com/explore',headers=headers)
print(response.text)

6.基本POST请求,需要构造formdata

import requests
data = {'name':'xiexie','age':33} #传个字典
response = requests.post('http://httpbin.org/post',data=data)
print(response.text)

response详解

  • response属性
import requests
response = requests.get('http://www.jianshu.com')
print(type(response.status_code),response.status_code)
print(type(response.headers),response.headers)
print(type(response.cookies),response.cookies)
print(type(response.url),response.url)
print(type(response.history),response.history)
import requests
response = requests.get('http://jianshu.com')
exit() if not response.status_code == 403 else print('Forbidden!')

request高级操作
1.文件上传

import requests
files = {'file':open('favicon.ico','rb')}
response = requests.post('http://httpbin.org/post',files=files)
print(response.text)

2.获取cookie

import requests
response = requests.get('https://www.baidu.com')
print(response.cookies)#response.cookies是一个列表
for key,value in response.cookies.items():
    print(key + "=" + value)

3.会话维持,用来模拟登陆用的。
模拟登陆 非常常用

import requests
requests.get('http://httpbin.org/cookies/set/number/1234567')
response = requests.get('http://httpbin.org/cookies')
print(response.text)
这里使用set设置了一个cookie,本意是下一句使用requests.get调用时希望返回这个cookie,实际返回cookies为空。实际上调用2次requests.get是互相独立的,相当于用不同的浏览器打开网页。如果想返回刚刚设置的cookie需要保持会话。以下是会话维持的代码,相当于用同一个浏览器打开。
import requests
s = requests.Session()
s.get('http://httpbin.org/cookies/set/number/1234567')
response = s.get('http://httpbin.org/cookies')
print(response.text)

返回值:{
"cookies": {
"number": "1234567"
}
}

证书验证
有时候打开https的网站,而这个网站提供的证书没有通过验证,那么抛出ssl错误导致程序中断。为了防止这种情况,可以用varify参数。

import requests
from requests.packages import urllib3
urllib3.disable_warnings()#调用原生的urllib3中的disable_warnings()可以消除警告信息。
response = requests.get('https://www.12306.cn',verify=False)
print(response.status_code)

也可以手动导入ca证书和key,这样也不会弹出错误

import requests
response = requests.get('https://www.12306.cn',cert={'parth/server.crt','/path/key'})
print(response.status_code)

代理设置

import request
proxies = {
    "http":"http://127.0.0.1:9998",
    "https":"https://127.0.0.1:9998",
}
response = requests.get("https://www.taobao.com",proxies=proxies)
print(response.status_code)

有用户名密码的代理

import request
proxies = {
    "http":"http://user:password@127.0.0.1:9998",
    }
response = requests.get("https://www.taobao.com",proxies=proxies)
print(response.status_code)

ssr这种类型的socks代理怎么使用?
安装:pip3 install 'requests[socks]'

import requests
proxies = {
    "http":"sock5://127.0.0.1:9998",
    "https":"sock5://127.0.0.1:9998",
}
response = requests.get("https://www.taobao.com",proxies=proxies)
print(response.status_code)
}

超时设置

import requests
try:
    response = requests.get("http://httpbin.org/get",timeout=1)
    print(response.status_code)
except requests.ReadTimeout:
    print('Timeout')

认证设置

import requests
response = requests.get("http://httpbin.org/get",auth=HTTPBasicAuth('user','123'))
print(response.status_code)

另一种字典的方式

import requests
response = requests.get("http://httpbin.org/get",auth={'user':'123'})
print(response.status_code)

异常处理,爬虫的异常处理也很有必要

import requests
from requests.exceptions import ReadTimeout,ConnectionError,RequestException
try:
    response = requests.get("http://httpbin.org/get",timeout=0.2)
    print(response.status_code)
except ReadTimeout:
    print('Timeout')
except ConnectionError:
    print("Con error")
except RequestException:
    print('Error')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • 上一篇:8.Urllib库基本使用下一篇:10.正则表达式基础 requests是python实现的最简单易用的H...
    在努力中阅读 3,311评论 2 11
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • 昨天,我们更多的讨论了request的基础API,让我们对它有了基础的认知。学会上一课程,我们已经能写点基本的爬虫...
    阿尔卑斯山上的小灰兔阅读 12,192评论 1 8
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,800评论 6 13
  • 相由心生 其实一个人的相貌是由心生出来的,要想让自己有气质,必须修炼内心,要想让人看起来好看,那必须要懂得衣服的搭配。
    天行健初九阅读 124评论 0 0