Python中requests庫(kù)的用法詳解
一、requests庫(kù)
requests是使用Apache2 licensed 許可證的HTTP庫(kù)。比urllib模塊更簡(jiǎn)潔。
Request支持HTTP連接保持和連接池,支持使用cookie保持會(huì)話,支持文件上傳,支持自動(dòng)響應(yīng)內(nèi)容的編碼,支持國(guó)際化的URL和POST數(shù)據(jù)自動(dòng)編碼。
在python內(nèi)置模塊的基礎(chǔ)上進(jìn)行了高度的封裝,從而使得python進(jìn)行網(wǎng)絡(luò)請(qǐng)求時(shí),變得人性化,使用Requests可以輕而易舉的完成瀏覽器可有的任何操作。
安裝
requests是第三方庫(kù),需要獨(dú)立安裝:pip install requests。requests是基于urllib編寫(xiě)的,并且使用起來(lái)非常方便,個(gè)人推薦使用requests。
官方中文教程地址:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
學(xué)習(xí)之前推薦一個(gè)非常好的http測(cè)試網(wǎng)站:http://httpbin.org,提供非常非常完善的接口調(diào)試、測(cè)試功能~
請(qǐng)求
requests支持http的各種請(qǐng)求,比如:
- GET: 請(qǐng)求指定的頁(yè)面信息,并返回實(shí)體主體。
- HEAD: 只請(qǐng)求頁(yè)面的首部。
- POST: 請(qǐng)求服務(wù)器接受所指定的文檔作為對(duì)所標(biāo)識(shí)的URI的新的從屬實(shí)體。
- PUT: 從客戶端向服務(wù)器傳送的數(shù)據(jù)取代指定的文檔的內(nèi)容。
- DELETE: 請(qǐng)求服務(wù)器刪除指定的頁(yè)面。
- OPTIONS: 允許客戶端查看服務(wù)器的性能。
訪問(wèn)baidu,獲取一些基本信息:
import requests
response = requests.get("https://www.baidu.com")# 打開(kāi)網(wǎng)頁(yè)獲取響應(yīng)
print('response:', type(response))# 打印響應(yīng)類(lèi)型,response:
print('status_code:', response.status_code)# 打印狀態(tài)碼 ,status_code: 200
print('cookie:', response.cookies)# 打印cookie ,cookie: ]></requestscookiejar[
print(type(response.text)) # 打印字符串形式的json響應(yīng)體的類(lèi)型 ,< class 'str'>
print('text:', response.text) # 打印字符串形式的響應(yīng)體 ,text: >?????...?
print('二進(jìn)制content:', response.content) # 二進(jìn)制content, b'\r\n\xe7\x99\xbb\xe5\xbd\x95... \r\n'
print('content:', response.content.decode("utf-8")) # content: 登錄...響應(yīng)
請(qǐng)求后響應(yīng)的內(nèi)容是requests.models.Response對(duì)象,需要處理后才能得到我們需要的信息。
requests自動(dòng)檢測(cè)編碼,可以使用encoding屬性查看。
無(wú)論響應(yīng)是文本還是二進(jìn)制內(nèi)容,我們都可以用content屬性獲得bytes對(duì)象:
- encoding:獲取當(dāng)前的編碼
- encoding = 'utf-8' :設(shè)置編碼
- headers :以字典對(duì)象存儲(chǔ)服務(wù)器響應(yīng)頭,但是這個(gè)字典比較特殊,字典鍵不區(qū)分大小寫(xiě),若鍵不存在則返回None
- requests.headers :返回發(fā)送到服務(wù)器的頭信息
- cookies :返回cookie
- history :返回重定向信息,當(dāng)然可以在請(qǐng)求是加上allow_redirects = false 阻止重定向
- status_code :響應(yīng)狀態(tài)碼
- raw :返回原始響應(yīng)體,也就是 urllib 的 response 對(duì)象,使用 r.raw.read()
- ok :查看r.ok的布爾值便可以知道是否登陸成功
- raise_for_status() :失敗請(qǐng)求(非200響應(yīng))拋出異常
- text: 得到的是str類(lèi)型,會(huì)自動(dòng)根據(jù)響應(yīng)頭部的字符編碼進(jìn)行解碼。
- content :得到的是bytes類(lèi)型,需要進(jìn)行解碼Response_get.content.decode(),相當(dāng)于Response_get.text。字節(jié)方式的響應(yīng)體,會(huì)自動(dòng)為你解碼 gzip 和 deflate 壓縮。
- json(): Requests中內(nèi)置的JSON解碼器,以json形式返回,前提返回的內(nèi)容確保是json格式的,不然解析出錯(cuò)會(huì)拋異常
其實(shí)使用requset.text避免亂碼的方式還有一個(gè),就是發(fā)出請(qǐng)求后,獲取內(nèi)容之前使用response.encoding屬性來(lái)改變編碼,例如:
response =requests.get("http://www.baidu.com")
#設(shè)置響應(yīng)內(nèi)容的編碼方式為utf-8
response.encoding="utf-8"
print(response.text)二、發(fā)送get請(qǐng)求
requests.get(url=url, headers=headers, params=params)
- url:請(qǐng)求url地址
- headers:請(qǐng)求頭
- params:查詢(xún)字符串
1、一個(gè)帶參數(shù)的get請(qǐng)求:
對(duì)于帶參數(shù)的URL,傳入一個(gè)dict作為params參數(shù),如果值為None的鍵不會(huì)被添加到url中。
import requests
#將參數(shù)寫(xiě)在字典里,通過(guò)params傳入,params接受字典或序列
data = {
"name": "hanson",
"age": 24
}
response = requests.get("http://httpbin.org/get", params=data) #發(fā)出一個(gè)get請(qǐng)求,獲得響應(yīng)
print(response.url) #打印url
print(response.text) #打印響應(yīng)內(nèi)容結(jié)果為:
http://httpbin.org/get?name=hanson&age=24
{
"args": {
"age": "24",
"name": "hanson"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5e71bb9d-79cfc9e0195befa018426f20"
},
"origin": "218.106.132.130",
"url": "http://httpbin.org/get?name=hanson&age=24"
}2、響應(yīng)json
requests的方便之處還在于,對(duì)于特定類(lèi)型的響應(yīng),例如JSON,可以直接獲?。?/p>
requests里的json方法就是封裝了json.loads方法。
import requests
import json
# 發(fā)出一個(gè)get請(qǐng)求
response = requests.get("http://httpbin.org/get")
# text響應(yīng)類(lèi)型
print(type(response.text))
# 直接解析響應(yīng)json(成字典)
print(response.json())
# 獲取響應(yīng)內(nèi)容后json進(jìn)行解析(成字典)
print(json.loads(response.text))
# 直接解析后的相應(yīng)內(nèi)容類(lèi)型
print(type(response.json()))控制臺(tái)打印結(jié)果:
<class 'str'>
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '124.74.47.82', 'url': 'http://httpbin.org/get'}
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '124.74.47.82', 'url': 'http://httpbin.org/get'}
< class 'dict'>3、添加頭信息headers
需要傳入HTTP Header時(shí),我們傳入一個(gè)dict作為headers參數(shù):
添加頭信息訪問(wèn):
import requests
# 添加頭部信息
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}
# 發(fā)送請(qǐng)求
response = requests.get("https://www.zhihu.com", headers=headers)
# 打印響應(yīng)
print(response.text)4、添加和獲取cookie信息
equests對(duì)Cookie做了特殊處理,使得我們不必解析Cookie就可以輕松獲取指定的Cookie:
要在請(qǐng)求中傳入Cookie,只需準(zhǔn)備一個(gè)dict傳入cookies參數(shù):
header = {'user-agent': 'my-app/0.0.1''}
cookie = {'key':'value'}
#發(fā)送請(qǐng)求
response = requests.get/post('your url',headers=header,cookies=cookie)
#打印cookie
print(response.cookies)
for key, value in response.cookies.items():
print(key + "=" + value)三、發(fā)送post請(qǐng)求
requests.post(url=url, headers=headers, data=params)
- url:請(qǐng)求url地址
- headers:請(qǐng)求頭
- data:發(fā)送編碼為表單形式的數(shù)據(jù)
1、一個(gè)帶參數(shù)的Post請(qǐng)求:
要發(fā)送POST請(qǐng)求,只需要把get()方法變成post(),然后傳入data參數(shù)作為POST請(qǐng)求的數(shù)據(jù):
import requests
#參數(shù)寫(xiě)在字典里
data = {
"name": "hason",
"age": 23
}
#請(qǐng)求時(shí)將字典參數(shù)賦給data參數(shù)
response = requests.post("http://httpbin.org/post", data=data)
#打印響應(yīng)
print(response.text)打印結(jié)果:
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "23",
"name": "zhaofan"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "19",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "124.74.47.82, 124.74.47.82",
"url": "https://httpbin.org/post"
}2、傳遞JSON數(shù)據(jù)
requests默認(rèn)使用application/x-www-form-urlencoded對(duì)POST數(shù)據(jù)編碼。如果要傳遞JSON數(shù)據(jù),可以直接傳入json參數(shù):
params = {'key': 'value'}
r = requests.post(url, json=params) # 內(nèi)部自動(dòng)序列化為JSON3、文件上傳
文件上傳需要用到請(qǐng)求參數(shù)里的files參數(shù):
在讀取文件時(shí),注意務(wù)必使用'rb'即二進(jìn)制模式讀取,這樣獲取的bytes長(zhǎng)度才是文件的長(zhǎng)度。
import requests
# rb,以只讀的方式打開(kāi)二進(jìn)制文件
files = {"files": open("a.jpg", "rb")}
# 發(fā)送post請(qǐng)求攜帶文件
response = requests.post("http://httpbin.org/post", files=files)
# 響應(yīng)內(nèi)容
print(response.text)響應(yīng)結(jié)果:
{
"args": {},
"data": "",
"files": {
"files": ""
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "145",
"Content-Type": "multipart/form-data; boundary=75c9d62b8f1248a9b6a89741143836b5",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "124.74.47.82, 124.74.47.82",
"url": "https://httpbin.org/post"
}request更加方便的是,可以把字符串當(dāng)作文件進(jìn)行上傳:
import requests
url = 'http://127.0.0.1:8080/upload'
files = {'file': ('test.txt', b'Hello Requests.')} #必需顯式的設(shè)置文件名
r = requests.post(url, files=files)
print(r.text)四、高級(jí)應(yīng)用
1、session會(huì)話維持
會(huì)話對(duì)象requests.Session能夠跨請(qǐng)求地保持某些參數(shù),比如cookies,即在同一個(gè)Session實(shí)例發(fā)出的所有請(qǐng)求都保持同一個(gè)cookies,而requests模塊每次會(huì)自動(dòng)處理cookies,這樣就很方便地處理登錄時(shí)的cookies問(wèn)題。
import requests
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, compress',
'Accept-Language': 'en-us;q=0.5,en;q=0.3',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}
#創(chuàng)建session對(duì)象
s = requests.Session()
s.headers.update(headers)#使用session訪問(wèn)并設(shè)置number參數(shù)
s.get("http://httpbin.org/cookies/set/number/123456")
#session對(duì)象再次訪問(wèn),獲取響應(yīng)內(nèi)容
response = s.get("http://httpbin.org/cookies")
print(response.text)2、身份驗(yàn)證
auth:認(rèn)證,接受元祖
基本身份認(rèn)證(HTTP Basic Auth)
import requests
from requests.auth import HTTPBasicAuth
r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))
print(r.json())簡(jiǎn)寫(xiě):
response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))另一種非常流行的HTTP身份認(rèn)證形式是摘要式身份認(rèn)證,Requests對(duì)它的支持也是開(kāi)箱即可用的:
requests.get(URL, auth=HTTPDigestAuth('user', 'pass')3、代理設(shè)置
proxies = {'http':'ip1','https':'ip2' }
requests.get('url',proxies=proxies)如果代理需要用戶名和密碼,則需要這樣:
proxies = {
"http": "http://user:pass@10.10.1.10:3128/",
}4、證書(shū)驗(yàn)證
現(xiàn)在的很多網(wǎng)站都是https的方式訪問(wèn),所以這個(gè)時(shí)候就涉及到證書(shū)的問(wèn)題
例如訪問(wèn)12306:
import requests
response = requests.get("https:/www.12306.cn")
print(response.status_code)會(huì)報(bào)錯(cuò),證書(shū)錯(cuò)誤
解決:加上verify=false(默認(rèn)是true)
import requests
#from requests.packages import urllib3
#urllib3.disable_warnings()
response = requests.get("https://www.12306.cn", verify=False)
print(response.status_code)5、超時(shí)時(shí)間
timeout,單位:毫秒
r = requests.get('url',timeout=1) #設(shè)置秒數(shù)超時(shí),僅對(duì)于連接有效6、重定向與請(qǐng)求歷史
使用GET或OPTIONS時(shí),Requests會(huì)自動(dòng)處理位置重定向。
Github將所有的HTTP請(qǐng)求重定向到HTTPS??梢允褂庙憫?yīng)對(duì)象的 history 方法來(lái)追蹤重定向。 我們來(lái)看看Github做了什么:
r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[]Response.history 是一個(gè):class:Request 對(duì)象的列表,為了完成請(qǐng)求而創(chuàng)建了這些對(duì)象。這個(gè)對(duì)象列表按照從最老到最近的請(qǐng)求進(jìn)行排序。
如果你使用的是GET或OPTIONS,那么你可以通過(guò) allow_redirects 參數(shù)禁用重定向處理:
r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]7、其他
- stream:是否下載獲取的內(nèi)容
- cert:保存本地SSL證書(shū)路徑
五、異常處理
所有的異常都是在requests.excepitons中:
示例:
import requests
from requests.exceptions import ReadTimeout,ConnectionError,RequestException
try:
response = requests.get("http://httpbin.org/get",timout=0.1)
print(response.status_code)
except ReadTimeout:
print("timeout")
except ConnectionError:
print("connection Error")
except RequestException:
print("error")測(cè)試可以發(fā)現(xiàn),首先被捕捉的異常是timeout超時(shí)異常,當(dāng)把網(wǎng)絡(luò)斷掉就會(huì)捕捉到ConnectionError連接異常,如果前面異常都沒(méi)有捕捉到,最后也可以通過(guò)RequestExctption捕捉到。
六、requests庫(kù)和urllib包對(duì)比
1、使用urllib.request
import urllib.parse
import urllib.request
url = "https://api.douban.com/v2/event/list"
params = urllib.parse.urlencode({'loc':'108288','day_type':'weekend','type':'exhibition'})
print(">>>>>>request params is:")
print(params)
# 發(fā)送請(qǐng)求
response = urllib.request.urlopen('?'.join([url, params]))
# 處理響應(yīng)
print(">>>>>>Response Headers:")
print(dict(response.info()))
print(">>>>>>Status Code:")
print(response.getcode())
print(">>>>>>Response body:")
print(response.read().decode())2、使用requests庫(kù)
import requests
url = "https://api.douban.com/v2/event/list"
params = {'loc':'108288','day_type':'weekend','type':'exhibition'}
print(">>>>>>request params is:")
print(params)
# 發(fā)送請(qǐng)求
response = requests.get(url=url,params=params)
# 處理響應(yīng)
print(">>>>>>Response Headers:")
print(response.headers)
print(">>>>>>Status Code:")
print(response.status_code)
print(">>>>>>Response body:")
print(response.text)3、區(qū)別:
- 構(gòu)建參數(shù):在構(gòu)建請(qǐng)求參數(shù)時(shí),第一種需要將請(qǐng)求參數(shù)使用urllib庫(kù)的urlencode方法進(jìn)行編碼預(yù)處理,非常麻煩。
- 請(qǐng)求方法:發(fā)送get請(qǐng)求時(shí),第一種使用的urllib庫(kù)的urlopen方法打開(kāi)一個(gè)url地址,而第二種直接使用requests庫(kù)的get方法,與http請(qǐng)求方式是對(duì)應(yīng)的,更加直接、易懂。
- 請(qǐng)求數(shù)據(jù):第一種按照url格式去拼接一個(gè)url字符串,顯然非常麻煩,第二種按順序?qū)et請(qǐng)求的url和參數(shù)寫(xiě)好就可以了。
- 處理響應(yīng):第一種處理消息頭部、響應(yīng)狀態(tài)碼和響應(yīng)正文時(shí)分別使用.info()、.getcode()、.read()方法,第二種使用.headers、.status_code、.text方法,方法名稱(chēng)與功能本身相對(duì)應(yīng),更方便理解、學(xué)習(xí)和使用。
- 連接方式:看一下返回?cái)?shù)據(jù)的頭信息的“connection”,使用urllib庫(kù)時(shí),“connection”:“close”,說(shuō)明每次請(qǐng)求結(jié)束關(guān)掉socket通道,而使用requests庫(kù)使用了urllib3,多次請(qǐng)求重復(fù)使用一個(gè)socket,“connection”:“keep-alive”,說(shuō)明多次請(qǐng)求使用一個(gè)連接,消耗更少的資源。
- 編碼方式:requests庫(kù)的編碼方式Accept-Encoding更全。
七、自動(dòng)登陸"示例:
1、抽屜新熱榜
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
# ############## 方式一 ##############
"""
# ## 1、首先登陸任何頁(yè)面,獲取cookie
i1 = requests.get(url="http://dig.chouti.com/help/service")
i1_cookies = i1.cookies.get_dict()
# ## 2、用戶登陸,攜帶上一次的cookie,后臺(tái)對(duì)cookie中的 gpsd 進(jìn)行授權(quán)
i2 = requests.post(
url="http://dig.chouti.com/login",
data={
'phone': "8615131255089",
'password': "xxooxxoo",
'oneMonth': ""
},
cookies=i1_cookies
)
# ## 3、點(diǎn)贊(只需要攜帶已經(jīng)被授權(quán)的gpsd即可)
gpsd = i1_cookies['gpsd']
i3 = requests.post(
url="http://dig.chouti.com/link/vote?linksId=8589523",
cookies={'gpsd': gpsd}
)
print(i3.text)
"""
# ############## 方式二 ##############
"""
import requests
session = requests.Session()
i1 = session.get(url="http://dig.chouti.com/help/service")
i2 = session.post(
url="http://dig.chouti.com/login",
data={
'phone': "8615131255089",
'password': "xxooxxoo",
'oneMonth': ""
}
)
i3 = session.post(
url="http://dig.chouti.com/link/vote?linksId=8589523"
)
print(i3.text)
"""2、 github
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
# ############## 方式一 ##############
#
# # 1. 訪問(wèn)登陸頁(yè)面,獲取 authenticity_token
# i1 = requests.get('https://github.com/login')
# soup1 = BeautifulSoup(i1.text, features='lxml')
# tag = soup1.find(name='input', attrs={'name': 'authenticity_token'})
# authenticity_token = tag.get('value')
# c1 = i1.cookies.get_dict()
# i1.close()
#
# # 1. 攜帶authenticity_token和用戶名密碼等信息,發(fā)送用戶驗(yàn)證
# form_data = {
# "authenticity_token": authenticity_token,
# "utf8": "",
# "commit": "Sign in",
# "login": "wupeiqi@live.com",
# 'password': 'xxoo'
# }
#
# i2 = requests.post('https://github.com/session', data=form_data, cookies=c1)
# c2 = i2.cookies.get_dict()
# c1.update(c2)
# i3 = requests.get('https://github.com/settings/repositories', cookies=c1)
#
# soup3 = BeautifulSoup(i3.text, features='lxml')
# list_group = soup3.find(name='div', class_='listgroup')
#
# from bs4.element import Tag
#
# for child in list_group.children:
# if isinstance(child, Tag):
# project_tag = child.find(name='a', class_='mr-1')
# size_tag = child.find(name='small')
# temp = "項(xiàng)目:%s(%s); 項(xiàng)目路徑:%s" % (project_tag.get('href'), size_tag.string, project_tag.string, )
# print(temp)
# ############## 方式二 ##############
# session = requests.Session()
# # 1. 訪問(wèn)登陸頁(yè)面,獲取 authenticity_token
# i1 = session.get('https://github.com/login')
# soup1 = BeautifulSoup(i1.text, features='lxml')
# tag = soup1.find(name='input', attrs={'name': 'authenticity_token'})
# authenticity_token = tag.get('value')
# c1 = i1.cookies.get_dict()
# i1.close()
#
# # 1. 攜帶authenticity_token和用戶名密碼等信息,發(fā)送用戶驗(yàn)證
# form_data = {
# "authenticity_token": authenticity_token,
# "utf8": "",
# "commit": "Sign in",
# "login": "wupeiqi@live.com",
# 'password': 'xxoo'
# }
#
# i2 = session.post('https://github.com/session', data=form_data)
# c2 = i2.cookies.get_dict()
# c1.update(c2)
# i3 = session.get('https://github.com/settings/repositories')
#
# soup3 = BeautifulSoup(i3.text, features='lxml')
# list_group = soup3.find(name='div', class_='listgroup')
#
# from bs4.element import Tag
#
# for child in list_group.children:
# if isinstance(child, Tag):
# project_tag = child.find(name='a', class_='mr-1')
# size_tag = child.find(name='small')
# temp = "項(xiàng)目:%s(%s); 項(xiàng)目路徑:%s" % (project_tag.get('href'), size_tag.string, project_tag.string, )
# print(temp)3、 知乎
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import requests
from bs4 import BeautifulSoup
session = requests.Session()
i1 = session.get(
url='https://www.zhihu.com/#signin',
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
}
)
soup1 = BeautifulSoup(i1.text, 'lxml')
xsrf_tag = soup1.find(name='input', attrs={'name': '_xsrf'})
xsrf = xsrf_tag.get('value')
current_time = time.time()
i2 = session.get(
url='https://www.zhihu.com/captcha.gif',
params={'r': current_time, 'type': 'login'},
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
})
with open('zhihu.gif', 'wb') as f:
f.write(i2.content)
captcha = input('請(qǐng)打開(kāi)zhihu.gif文件,查看并輸入驗(yàn)證碼:')
form_data = {
"_xsrf": xsrf,
'password': 'xxooxxoo',
"captcha": 'captcha',
'email': '424662508@qq.com'
}
i3 = session.post(
url='https://www.zhihu.com/login/email',
data=form_data,
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
}
)
i4 = session.get(
url='https://www.zhihu.com/settings/profile',
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
}
)
soup4 = BeautifulSoup(i4.text, 'lxml')
tag = soup4.find(id='rename-section')
nick_name = tag.find('span',class_='name').string
print(nick_name)4、 博客園
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
import json
import base64
import rsa
import requests
def js_encrypt(text):
b64der = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCp0wHYbg/NOPO3nzMD3dndwS0MccuMeXCHgVlGOoYyFwLdS24Im2e7YyhB0wrUsyYf0/nhzCzBK8ZC9eCWqd0aHbdgOQT6CuFQBMjbyGYvlVYU2ZP7kG9Ft6YV6oc9ambuO7nPZh+bvXH0zDKfi02prknrScAKC0XhadTHT3Al0QIDAQAB'
der = base64.standard_b64decode(b64der)
pk = rsa.PublicKey.load_pkcs1_openssl_der(der)
v1 = rsa.encrypt(bytes(text, 'utf8'), pk)
value = base64.encodebytes(v1).replace(b'\n', b'')
value = value.decode('utf8')
return value
session = requests.Session()
i1 = session.get('https://passport.cnblogs.com/user/signin')
rep = re.compile("'VerificationToken': '(.*)'")
v = re.search(rep, i1.text)
verification_token = v.group(1)
form_data = {
'input1': js_encrypt('wptawy'),
'input2': js_encrypt('asdfasdf'),
'remember': False
}
i2 = session.post(url='https://passport.cnblogs.com/user/signin',
data=json.dumps(form_data),
headers={
'Content-Type': 'application/json; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'VerificationToken': verification_token}
)
i3 = session.get(url='https://i.cnblogs.com/EditDiary.aspx')
print(i3.text)5、 拉勾網(wǎng)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
# 第一步:訪問(wèn)登陸頁(yè),拿到X_Anti_Forge_Token,X_Anti_Forge_Code
# 1、請(qǐng)求url:https://passport.lagou.com/login/login.html
# 2、請(qǐng)求方法:GET
# 3、請(qǐng)求頭:
# User-agent
r1 = requests.get('https://passport.lagou.com/login/login.html',
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
},
)
X_Anti_Forge_Token = re.findall("X_Anti_Forge_Token = '(.*?)'", r1.text, re.S)[0]
X_Anti_Forge_Code = re.findall("X_Anti_Forge_Code = '(.*?)'", r1.text, re.S)[0]
print(X_Anti_Forge_Token, X_Anti_Forge_Code)
# print(r1.cookies.get_dict())
# 第二步:登陸
# 1、請(qǐng)求url:https://passport.lagou.com/login/login.json
# 2、請(qǐng)求方法:POST
# 3、請(qǐng)求頭:
# cookie
# User-agent
# Referer:https://passport.lagou.com/login/login.html
# X-Anit-Forge-Code:53165984
# X-Anit-Forge-Token:3b6a2f62-80f0-428b-8efb-ef72fc100d78
# X-Requested-With:XMLHttpRequest
# 4、請(qǐng)求體:
# isValidate:true
# username:15131252215
# password:ab18d270d7126ea65915c50288c22c0d
# request_form_verifyCode:''
# submit:''
r2 = requests.post(
'https://passport.lagou.com/login/login.json',
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'Referer': 'https://passport.lagou.com/login/login.html',
'X-Anit-Forge-Code': X_Anti_Forge_Code,
'X-Anit-Forge-Token': X_Anti_Forge_Token,
'X-Requested-With': 'XMLHttpRequest'
},
data={
"isValidate": True,
'username': '15131255089',
'password': 'ab18d270d7126ea65915c50288c22c0d',
'request_form_verifyCode': '',
'submit': ''
},
cookies=r1.cookies.get_dict()
)
print(r2.text)到此這篇關(guān)于Python使用requests庫(kù)的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python中循環(huán)后使用list.append()數(shù)據(jù)被覆蓋問(wèn)題的解決
這篇文章主要給大家介紹了關(guān)于Python中循環(huán)后使用list.append()數(shù)據(jù)被覆蓋問(wèn)題的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07
python+OpenCV實(shí)現(xiàn)車(chē)牌號(hào)碼識(shí)別
這篇文章主要介紹了python+OpenCV實(shí)現(xiàn)車(chē)牌號(hào)碼識(shí)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11
PyTorch?Tensor創(chuàng)建實(shí)現(xiàn)
本文主要介紹了PyTorch?Tensor創(chuàng)建實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
學(xué)習(xí)python需要有編程基礎(chǔ)嗎
在本篇文章里小編給大家分享的是一篇關(guān)于學(xué)習(xí)python有哪些必要條件,需要的朋友們可以學(xué)習(xí)下。2020-06-06
Python入門(mén)教程(四十)Python的NumPy數(shù)組創(chuàng)建
這篇文章主要介紹了Python入門(mén)教程(四十)Python的NumPy數(shù)組創(chuàng)建,NumPy 用于處理數(shù)組,NumPy 中的數(shù)組對(duì)象稱(chēng)為 ndarray,我們可以使用 array() 函數(shù)創(chuàng)建一個(gè) NumPy ndarray 對(duì)象,需要的朋友可以參考下2023-05-05

