網路請求
1.urllib庫 —內置
urlopen函式:
創建一個表示遠程url的類檔案物件,然后像本地檔案一樣操作這個類檔案物件來獲取遠程資料,
url:請求的url,
data:請求的data,如果設定了這個值,那么將變成post請求,
回傳值:回傳值是一個http.client.HTTPResponse物件,這個物件是一個類檔案句柄物件,有read(size)、readline、readlines以及getcode等方法,
urlretrieve函式:
這個函式可以方便的將網頁上的一個檔案保存到本地,
request.urlretrieve(url,檔案名)
urlencode函式:編碼
urlencode可以把字典資料轉換為URL編碼的資料,
from urllib import parse
data = {'name':'老王','age':18,'greet':'hello world'}
qs = parse.urlencode(data)
print(qs)
#name=%E8%80%81%E7%8E%8B&age=18&greet=hello+world
parse_qs函式:解碼
可以將經過編碼后的url引數進行解碼
print(parse.parse_qs(qs))
# {'name': ['老王'], 'age': ['18'], 'greet': ['hello world']}
urlparse和urlsplit函式:決議url
from urllib import parse
url = 'http://www.baidu.com/index.html;user?id=S#comment'
result = parse.urlparse(url)
# result = parse.urlsplit(url)
print(result)
print(result.scheme)
print(result.netloc)
print(result.path)
#urlparse里有params屬性,而urlsplit沒有這個params屬性,
print(result.params)
request.Request類:網路請求 可以增加請求頭
from urllib import request
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
rq = request.Request('https://www.baidu.com/',headers=headers)
resp = request.urlopen(rq)
print(resp.read())
ProxyHandler處理器(代理設定):封ip問題
-
代理原理:在請求目的網站之前,先請求代理服務器,然后讓代理服務器去請求目的網站,代理服務器拿到目的網站的資料后,再轉發給我們的代碼,
-
http://httpbin.org:這個網站可以方便的查看http請求的一些引數,
-
在代碼中使用代理 示例:
# 使用代理 # 步驟 url = 'http://httpbin.org/ip' #1. 使用ProxyHandler,傳入代理構建一個handler handler = request.ProxyHandler({'http':'122.193.244.243:9999'}) #2. 使用上面創建的handler構建一個opener opener = request.build_opener(handler) #3. 使用opener去發送一個請求 resp = opener.open(url) print(resp.read())
cookie: 登錄
-
什么是cookie:指某些網站為了辨別用戶身份、進行 session 跟蹤而儲存在用戶本地終端上的資料
-
cookie的格式:
Set-Cookie: NAME=VALUE;Expires/Max-age=DATE;Path=PATH; Domain=DOMAIN_NAME;SECURE
引數意義:
NAME:cookie的名字,
VALUE:cookie的值,
Expires:cookie的過期時間,
Path:cookie作用的路徑,
Domain:cookie作用的域名,
SECURE:是否只在https協議下起作用,
http.cookiejar模塊:提供用于存盤cookie的物件
-
CookieJar:管理HTTP cookie值、存盤HTTP請求生成的cookie、向傳出的HTTP請求添加cookie的物件,整個cookie都存盤在記憶體中,對CookieJar實體進行垃圾回收后cookie也將丟失,
-
FileCookieJar (filename,delayload=None,policy=None):從CookieJar派生而來,用來創建FileCookieJar實體,檢索cookie資訊并將cookie存盤到檔案中,filename是存盤cookie的檔案名,delayload為True時支持延遲訪問訪問檔案,即只有在需要時才讀取檔案或在檔案中存盤資料,
-
MozillaCookieJar (filename,delayload=None,policy=None):從FileCookieJar派生而來,創建與Mozilla瀏覽器 cookies.txt兼容的FileCookieJar實體,
-
LWPCookieJar (filename,delayload=None,policy=None):從FileCookieJar派生而來,創建與libwww-perl標準的 Set-Cookie3 檔案格式兼容的FileCookieJar實體,
實體:
from urllib import request
from urllib import parse
from http.cookiejar import CookieJar
# 登錄:https://i.meishi.cc/login.php?redirect=https%3A%2F%2Fwww.meishij.net%2F
#個人網頁https://i.meishi.cc/cook.php?id=13686422
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
#1.登錄
#1.1 創建cookiejar物件
cookiejar = CookieJar()
#1.2 使用cookiejar創建一個HTTPCookieProcess物件
handler = request.HTTPCookieProcessor(cookiejar)
#1.3 使用上一步的創建的handler創建一個opener
opener = request.build_opener(handler)
#1.4 使用opener發送登錄請求 (賬號和密碼)
post_url = 'https://i.meishi.cc/login.php?redirect=https%3A%2F%2Fwww.meishij.net%2F'
post_data = parse.urlencode({
'username':'1097566154@qq.com',
'password':'wq15290884759.'
})
req = request.Request(post_url,data=post_data.encode('utf-8'))
opener.open(req)
#2.訪問個人網頁
url = 'https://i.meishi.cc/cook.php?id=13686422'
rq = request.Request(url,headers=headers)
resp = opener.open(rq)
print(resp.read().decode('utf-8'))
cookie加載與保存
from urllib import request
from http.cookiejar import MozillaCookieJar
# 保存
# cookiejar = MozillaCookieJar('cookie.txt')
# handler = request.HTTPCookieProcessor(cookiejar)
# opener = request.build_opener(handler)
# resp = opener.open('http://www.httpbin.org/cookies/set/course/abc')
#
# cookiejar.save(ignore_discard=True,ignore_expires=True)
# ignore_discard=True 即使cookies即將被丟棄也要保存下來
# ignore_expires=True 如果cookies已經過期也將它保存并且檔案已存在時將覆寫
#加載
cookiejar = MozillaCookieJar('cookie.txt')
cookiejar.load()
handler = request.HTTPCookieProcessor(cookiejar)
opener = request.build_opener(handler)
resp = opener.open('http://www.httpbin.org/cookies/set/course/abc')
for cookie in cookiejar:
print(cookie)
2.requests庫 —第三方庫
Requests:讓HTTP服務人類
安裝和檔案地址:
pip install requests
發送GET請求
import requests
# 添加headers和查詢引數
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
kw = {'wd':'中國'}
# params 接收一個字典或者字串的查詢引數,字典型別自動轉換為url編碼,不需要urlencode()
response = requests.get('https://www.baidu.com/s',headers=headers,params=kw)
print(response)
# 屬性
# 查詢回應內容
print(response.text) #回傳unicode格式的資料
print(response.content) #回傳位元組流資料
print(response.url) #查看完整url地址
print(response.encoding) # 查看回應頭部字符編碼
response.text和response.content的區別:
response.content:這個是直接從網路上抓取的資料,沒有經過任何的編碼,所以是一個bytes型別,其實在硬碟上和網路上傳輸的字串都是bytes型別response.text:這個是str的資料型別,是requests庫將response.content進行解碼的字串,解碼需要指定一個編碼方式,requests會根據自己的猜測來判斷編碼的方式,所以有時候可能會猜測錯誤,就會導致解碼產生亂碼,這時候就應該進行手動解碼,比如使用response.content.decode('utf-8')
發送POST請求:
response = requests.post("http://www.baidu.com/",data=data)
POST請求方式
import requests
url = 'https://i.meishi.cc/login.php?redirect=https%3A%2F%2Fwww.meishij.net%2F'
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
data = {
'redirect': 'https://www.meishij.net/',
'username': '1097566154@qq.com',
'password': 'wq15290884759.'
}
resp = requests.post(url,headers=headers,data=data)
print(resp.text)
使用代理:
只要在請求的方法中(比如get或者post)傳遞proxies引數就可以了,
import requests
proxy = {
'http':'111.77.197.127:9999'
}
url = 'http://www.httpbin.org/ip'
resp = requests.get(url,proxies=proxy)
print(resp.text)
cookie:
基本使用:模擬登陸
import requests
url = 'https://www.zhihu.com/hot'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
'cookie':'_zap=59cde9c3-c5c0-4baa-b756-fa16b5e72b10; d_c0="APDi1NJcuQ6PTvP9qa1EKY6nlhVHc_zYWGM=|1545737641"; __gads=ID=237616e597ec37ad:T=1546339385:S=ALNI_Mbo2JturZesh38v7GzEeKjlADtQ5Q; _xsrf=pOd30ApWQ2jihUIfq94gn2UXxc0zEeay; q_c1=1767e338c3ab416692e624763646fc07|1554209209000|1545743740000; tst=h; __utma=51854390.247721793.1554359436.1554359436.1554359436.1; __utmc=51854390; __utmz=51854390.1554359436.1.1.utmcsr=zhihu.com|utmccn=(referral)|utmcmd=referral|utmcct=/hot; __utmv=51854390.100-1|2=registration_date=20180515=1^3=entry_date=20180515=1; l_n_c=1; l_cap_id="OWRiYjI0NzJhYzYwNDM3MmE2ZmIxMGIzYmQwYzgzN2I=|1554365239|875ac141458a2ebc478680d99b9219c461947071"; r_cap_id="MmZmNDFkYmIyM2YwNDAxZmJhNWU1NmFjOGRkNDNjYjc=|1554365239|54372ab1797cba8c4dd224ba1845dd7d3f851802"; cap_id="YzQwNGFlYWNmNjY3NDFhNGI4MGMyYjZjYjRhMzQ1ZmE=|1554365239|385cc25e3c4e3b0b68ad5747f623cf3ad2955c9f"; n_c=1; capsion_ticket="2|1:0|10:1554366287|14:capsion_ticket|44:MmE5YzNkYjgzODAyNDgzNzg5MTdjNmE3NjQyODllOGE=|40d3498bedab1b7ba1a247d9fc70dc0e4f9a4f394d095b0992a4c85e32fd29be"; z_c0="2|1:0|10:1554366318|4:z_c0|92:Mi4xOWpCeUNRQUFBQUFBOE9MVTBseTVEaVlBQUFCZ0FsVk5iZzJUWFFEWi1JMkxnQXlVUXh2SlhYb3NmWks3d1VwMXRB|81b45e01da4bc235c2e7e535d580a8cc07679b50dac9e02de2711e66c65460c6"; tgw_l7_route=578107ff0d4b4f191be329db6089ff48'
}
resp = requests.get(url,headers=headers)
print(resp.text)
session:共享cookie
案例:
post_url = 'https://i.meishi.cc/login.php?redirect=https%3A%2F%2Fwww.meishij.net%2F'
post_data = {
'username':'1097566154@qq.com',
'password':'wq15290884759.'
}
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
# 登錄
session = requests.session()
session.post(post_url,headers=headers,data=post_data)
#訪問個人網頁
url = 'https://i.meishi.cc/cook.php?id=13686422'
resp = session.get(url)
print(resp.text)
處理不信任的SSL證書:
對于那些已經被信任的SSL證書的網站,比如https://www.baidu.com/,那么使用requests直接就可以正常的回傳回應,示例代碼如下:
resp = requests.get('https://inv-veri.chinatax.gov.cn/',verify=False)
print(resp.content.decode('utf-8'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/20064.html
標籤:其他
