欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中requests庫的用法詳解

 更新時間:2022年06月03日 10:40:01   作者:springsnow  
本文詳細講解了Python中requests庫的用法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、requests庫

requests是使用Apache2 licensed 許可證的HTTP庫。比urllib模塊更簡潔。

Request支持HTTP連接保持和連接池,支持使用cookie保持會話,支持文件上傳,支持自動響應(yīng)內(nèi)容的編碼,支持國際化的URL和POST數(shù)據(jù)自動編碼。

在python內(nèi)置模塊的基礎(chǔ)上進行了高度的封裝,從而使得python進行網(wǎng)絡(luò)請求時,變得人性化,使用Requests可以輕而易舉的完成瀏覽器可有的任何操作。

安裝

requests是第三方庫,需要獨立安裝:pip install requests。requests是基于urllib編寫的,并且使用起來非常方便,個人推薦使用requests。

官方中文教程地址:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

學(xué)習(xí)之前推薦一個非常好的http測試網(wǎng)站:http://httpbin.org,提供非常非常完善的接口調(diào)試、測試功能~

請求

requests支持http的各種請求,比如:

  • GET: 請求指定的頁面信息,并返回實體主體。
  • HEAD: 只請求頁面的首部。
  • POST: 請求服務(wù)器接受所指定的文檔作為對所標識的URI的新的從屬實體。
  • PUT: 從客戶端向服務(wù)器傳送的數(shù)據(jù)取代指定的文檔的內(nèi)容。
  • DELETE: 請求服務(wù)器刪除指定的頁面。
  • OPTIONS: 允許客戶端查看服務(wù)器的性能。

訪問baidu,獲取一些基本信息:

import requests

response = requests.get("https://www.baidu.com")# 打開網(wǎng)頁獲取響應(yīng)
print('response:', type(response))# 打印響應(yīng)類型,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)體的類型 ,< class 'str'>
print('text:', response.text)   # 打印字符串形式的響應(yīng)體 ,text: >?????...?
print('二進制content:', response.content)       # 二進制content, b'\r\n\xe7\x99\xbb\xe5\xbd\x95... \r\n'
print('content:', response.content.decode("utf-8")) # content:  登錄...

響應(yīng)

請求后響應(yīng)的內(nèi)容是requests.models.Response對象,需要處理后才能得到我們需要的信息。

requests自動檢測編碼,可以使用encoding屬性查看。

無論響應(yīng)是文本還是二進制內(nèi)容,我們都可以用content屬性獲得bytes對象:

  • encoding:獲取當(dāng)前的編碼
  • encoding = 'utf-8' :設(shè)置編碼
  • headers :以字典對象存儲服務(wù)器響應(yīng)頭,但是這個字典比較特殊,字典鍵不區(qū)分大小寫,若鍵不存在則返回None
  • requests.headers :返回發(fā)送到服務(wù)器的頭信息
  • cookies :返回cookie
  • history :返回重定向信息,當(dāng)然可以在請求是加上allow_redirects = false 阻止重定向
  • status_code :響應(yīng)狀態(tài)碼
  • raw :返回原始響應(yīng)體,也就是 urllib 的 response 對象,使用 r.raw.read()
  • ok :查看r.ok的布爾值便可以知道是否登陸成功
  • raise_for_status() :失敗請求(非200響應(yīng))拋出異常
  • text: 得到的是str類型,會自動根據(jù)響應(yīng)頭部的字符編碼進行解碼。
  • content :得到的是bytes類型,需要進行解碼Response_get.content.decode(),相當(dāng)于Response_get.text。字節(jié)方式的響應(yīng)體,會自動為你解碼 gzip 和 deflate 壓縮。
  • json(): Requests中內(nèi)置的JSON解碼器,以json形式返回,前提返回的內(nèi)容確保是json格式的,不然解析出錯會拋異常

其實使用requset.text避免亂碼的方式還有一個,就是發(fā)出請求后,獲取內(nèi)容之前使用response.encoding屬性來改變編碼,例如:

response =requests.get("http://www.baidu.com")
 #設(shè)置響應(yīng)內(nèi)容的編碼方式為utf-8
response.encoding="utf-8"
print(response.text)

二、發(fā)送get請求

requests.get(url=url, headers=headers, params=params)
  • url:請求url地址
  • headers:請求頭
  • params:查詢字符串

1、一個帶參數(shù)的get請求:

對于帶參數(shù)的URL,傳入一個dict作為params參數(shù),如果值為None的鍵不會被添加到url中。

import requests
    #將參數(shù)寫在字典里,通過params傳入,params接受字典或序列
    data = {
        "name": "hanson",
        "age": 24
    }
   response = requests.get("http://httpbin.org/get", params=data) #發(fā)出一個get請求,獲得響應(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的方便之處還在于,對于特定類型的響應(yīng),例如JSON,可以直接獲?。?/p>

requests里的json方法就是封裝了json.loads方法。

import requests
import json
# 發(fā)出一個get請求
response = requests.get("http://httpbin.org/get")
# text響應(yīng)類型
print(type(response.text))
# 直接解析響應(yīng)json(成字典)
print(response.json())
# 獲取響應(yīng)內(nèi)容后json進行解析(成字典)
print(json.loads(response.text))
# 直接解析后的相應(yīng)內(nèi)容類型
print(type(response.json()))

控制臺打印結(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時,我們傳入一個dict作為headers參數(shù):

添加頭信息訪問:

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ā)送請求
response = requests.get("https://www.zhihu.com", headers=headers)
# 打印響應(yīng)
print(response.text)

4、添加和獲取cookie信息

equests對Cookie做了特殊處理,使得我們不必解析Cookie就可以輕松獲取指定的Cookie:

要在請求中傳入Cookie,只需準備一個dict傳入cookies參數(shù):

header = {'user-agent': 'my-app/0.0.1''}
cookie = {'key':'value'}
 #發(fā)送請求
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請求

requests.post(url=url, headers=headers, data=params)
  • url:請求url地址
  • headers:請求頭
  • data:發(fā)送編碼為表單形式的數(shù)據(jù)

1、一個帶參數(shù)的Post請求:

要發(fā)送POST請求,只需要把get()方法變成post(),然后傳入data參數(shù)作為POST請求的數(shù)據(jù):

import requests
    #參數(shù)寫在字典里
    data = {
        "name": "hason",
         "age": 23
     }
     #請求時將字典參數(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默認使用application/x-www-form-urlencoded對POST數(shù)據(jù)編碼。如果要傳遞JSON數(shù)據(jù),可以直接傳入json參數(shù):

params = {'key': 'value'}
r = requests.post(url, json=params) # 內(nèi)部自動序列化為JSON

3、文件上傳

文件上傳需要用到請求參數(shù)里的files參數(shù):

在讀取文件時,注意務(wù)必使用'rb'即二進制模式讀取,這樣獲取的bytes長度才是文件的長度。

import requests
# rb,以只讀的方式打開二進制文件
files = {"files": open("a.jpg", "rb")}
# 發(fā)送post請求攜帶文件
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)作文件進行上傳:

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)

四、高級應(yīng)用

1、session會話維持

會話對象requests.Session能夠跨請求地保持某些參數(shù),比如cookies,即在同一個Session實例發(fā)出的所有請求都保持同一個cookies,而requests模塊每次會自動處理cookies,這樣就很方便地處理登錄時的cookies問題。

    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對象
    s = requests.Session()
    s.headers.update(headers)#使用session訪問并設(shè)置number參數(shù)
    s.get("http://httpbin.org/cookies/set/number/123456")
    #session對象再次訪問,獲取響應(yīng)內(nèi)容
    response = s.get("http://httpbin.org/cookies")
    print(response.text)

2、身份驗證

auth:認證,接受元祖

基本身份認證(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())

簡寫:

response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))

另一種非常流行的HTTP身份認證形式是摘要式身份認證,Requests對它的支持也是開箱即可用的:

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、證書驗證

現(xiàn)在的很多網(wǎng)站都是https的方式訪問,所以這個時候就涉及到證書的問題

例如訪問12306:

import requests
response = requests.get("https:/www.12306.cn")
print(response.status_code)

會報錯,證書錯誤

解決:加上verify=false(默認是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、超時時間

timeout,單位:毫秒

r = requests.get('url',timeout=1)           #設(shè)置秒數(shù)超時,僅對于連接有效

6、重定向與請求歷史

使用GET或OPTIONS時,Requests會自動處理位置重定向。

Github將所有的HTTP請求重定向到HTTPS。可以使用響應(yīng)對象的 history 方法來追蹤重定向。 我們來看看Github做了什么:

r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[]

Response.history 是一個:class:Request 對象的列表,為了完成請求而創(chuàng)建了這些對象。這個對象列表按照從最老到最近的請求進行排序。

如果你使用的是GET或OPTIONS,那么你可以通過 allow_redirects 參數(shù)禁用重定向處理:

r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]

7、其他

  • stream:是否下載獲取的內(nèi)容
  • cert:保存本地SSL證書路徑

五、異常處理

所有的異常都是在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")

測試可以發(fā)現(xiàn),首先被捕捉的異常是timeout超時異常,當(dāng)把網(wǎng)絡(luò)斷掉就會捕捉到ConnectionError連接異常,如果前面異常都沒有捕捉到,最后也可以通過RequestExctption捕捉到。

六、requests庫和urllib包對比

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ā)送請求
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庫

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ā)送請求
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)建請求參數(shù)時,第一種需要將請求參數(shù)使用urllib庫的urlencode方法進行編碼預(yù)處理,非常麻煩。
  • 請求方法:發(fā)送get請求時,第一種使用的urllib庫的urlopen方法打開一個url地址,而第二種直接使用requests庫的get方法,與http請求方式是對應(yīng)的,更加直接、易懂。
  • 請求數(shù)據(jù):第一種按照url格式去拼接一個url字符串,顯然非常麻煩,第二種按順序?qū)et請求的url和參數(shù)寫好就可以了。
  • 處理響應(yīng):第一種處理消息頭部、響應(yīng)狀態(tài)碼和響應(yīng)正文時分別使用.info()、.getcode()、.read()方法,第二種使用.headers、.status_code、.text方法,方法名稱與功能本身相對應(yīng),更方便理解、學(xué)習(xí)和使用。
  • 連接方式:看一下返回數(shù)據(jù)的頭信息的“connection”,使用urllib庫時,“connection”:“close”,說明每次請求結(jié)束關(guān)掉socket通道,而使用requests庫使用了urllib3,多次請求重復(fù)使用一個socket,“connection”:“keep-alive”,說明多次請求使用一個連接,消耗更少的資源。
  • 編碼方式:requests庫的編碼方式Accept-Encoding更全。

七、自動登陸"示例:

1、抽屜新熱榜

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests


# ############## 方式一 ##############
"""
# ## 1、首先登陸任何頁面,獲取cookie
i1 = requests.get(url="http://dig.chouti.com/help/service")
i1_cookies = i1.cookies.get_dict()

# ## 2、用戶登陸,攜帶上一次的cookie,后臺對cookie中的 gpsd 進行授權(quán)
i2 = requests.post(
    url="http://dig.chouti.com/login",
    data={
        'phone': "8615131255089",
        'password': "xxooxxoo",
        'oneMonth': ""
    },
    cookies=i1_cookies
)

# ## 3、點贊(只需要攜帶已經(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. 訪問登陸頁面,獲取 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ā)送用戶驗證
# 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 = "項目:%s(%s); 項目路徑:%s" % (project_tag.get('href'), size_tag.string, project_tag.string, )
#         print(temp)



# ############## 方式二 ##############
# session = requests.Session()
# # 1. 訪問登陸頁面,獲取 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ā)送用戶驗證
# 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 = "項目:%s(%s); 項目路徑:%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('請打開zhihu.gif文件,查看并輸入驗證碼:')
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


# 第一步:訪問登陸頁,拿到X_Anti_Forge_Token,X_Anti_Forge_Code
# 1、請求url:https://passport.lagou.com/login/login.html
# 2、請求方法:GET
# 3、請求頭:
#    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、請求url:https://passport.lagou.com/login/login.json
# 2、請求方法:POST
# 3、請求頭:
#    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、請求體:
# 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庫的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python中循環(huán)后使用list.append()數(shù)據(jù)被覆蓋問題的解決

    Python中循環(huán)后使用list.append()數(shù)據(jù)被覆蓋問題的解決

    這篇文章主要給大家介紹了關(guān)于Python中循環(huán)后使用list.append()數(shù)據(jù)被覆蓋問題的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-07-07
  • Python的ini配置文件你了解嗎

    Python的ini配置文件你了解嗎

    這篇文章主要為大家詳細介紹了Python的ini配置文件,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • python+OpenCV實現(xiàn)車牌號碼識別

    python+OpenCV實現(xiàn)車牌號碼識別

    這篇文章主要介紹了python+OpenCV實現(xiàn)車牌號碼識別,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-11-11
  • python3將變量輸入的簡單實例

    python3將變量輸入的簡單實例

    在本篇文章里小編給大家整理的是一篇關(guān)于python3將變量輸入的簡單實例內(nèi)容,有需要的朋友們可以參考下。
    2020-08-08
  • Python函數(shù)基礎(chǔ)

    Python函數(shù)基礎(chǔ)

    這篇文章主要從函數(shù)開始介紹展開Python函數(shù),以最基本的函數(shù)定義方法描述,需要的朋友可以參考下文簡單的介紹
    2021-08-08
  • PyTorch?Tensor創(chuàng)建實現(xiàn)

    PyTorch?Tensor創(chuàng)建實現(xiàn)

    本文主要介紹了PyTorch?Tensor創(chuàng)建實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • 學(xué)習(xí)python需要有編程基礎(chǔ)嗎

    學(xué)習(xí)python需要有編程基礎(chǔ)嗎

    在本篇文章里小編給大家分享的是一篇關(guān)于學(xué)習(xí)python有哪些必要條件,需要的朋友們可以學(xué)習(xí)下。
    2020-06-06
  • Python入門教程(四十)Python的NumPy數(shù)組創(chuàng)建

    Python入門教程(四十)Python的NumPy數(shù)組創(chuàng)建

    這篇文章主要介紹了Python入門教程(四十)Python的NumPy數(shù)組創(chuàng)建,NumPy 用于處理數(shù)組,NumPy 中的數(shù)組對象稱為 ndarray,我們可以使用 array() 函數(shù)創(chuàng)建一個 NumPy ndarray 對象,需要的朋友可以參考下
    2023-05-05
  • 壓縮包密碼破解示例分享(類似典破解)

    壓縮包密碼破解示例分享(類似典破解)

    有一個壓縮包密碼忘了,寫了一個小腳本實現(xiàn)一個解密的功能,輸入自己常用密碼中的單詞后,腳本將這些密碼組合嘗試解壓壓縮包
    2014-01-01
  • python列表的常用操作方法小結(jié)

    python列表的常用操作方法小結(jié)

    這篇文章主要為大家詳細介紹了python字典的常用操作方法,主要內(nèi)容包含Python中列表(List)的詳解操作方法,包含創(chuàng)建、訪問、更新、刪除、其它操作等,需要的朋友可以參考下
    2016-05-05

最新評論