請求庫 urllib 與 requests

urllib模塊

urllib是Python自帶的一個用于爬蟲的庫,其主要作用就是可以通過代碼模擬瀏覽器發(fā)送請求。其常被用到的子模塊在Python3中的為urllib.request和urllib.parse,在Python2中是urllib和urllib2。

一、使用流程:
  • 指定url
  • 基于urllib的request子模塊發(fā)起請求
  • 獲取響應中的數(shù)據(jù)值
  • 持久化存儲
二、urlopen函數(shù)原型:

urllib.request.urlopen(url, data=None, timeout=<object object at 0x10af327d0>, *, cafile=None, capath=None, cadefault=False, context=None)
在日常開發(fā)中,我們能用的只有url和data這兩個參數(shù)

  • url參數(shù):指定向哪個url發(fā)起請求
  • url的特性:url必須為ASCII編碼的數(shù)據(jù)值。所以我們在爬蟲代碼中編寫url時,如果url中存在非ASCII編碼的數(shù)據(jù)值,則必須對其進行ASCII編碼后,該url方可被使用。
    • get: word = urllib.parse.quote("人民幣")
    • post: data = { 'kw':'西瓜'} data = urllib.parse.urlencode(data) data = data.encode() urlencode(返回值類型為str)
  • data參數(shù):可以將post請求中攜帶的參數(shù)封裝成字典的形式傳遞給該參數(shù)
  • urlopen函數(shù)返回的響應對象,相關函數(shù)調用介紹:
    • response.headers():獲取響應頭信息
    • response.getcode():獲取響應狀態(tài)碼
    • response.geturl():獲取請求的url
    • response.read():獲取響應中的數(shù)據(jù)值(字節(jié)類型)
三、其他
  • 爬機制:網(wǎng)站檢查請求的UA,如果發(fā)現(xiàn)UA是爬蟲程序,則拒絕提供網(wǎng)站數(shù)據(jù)。
  • User-Agent(UA):請求載體的身份標識.
  • 反反爬機制:偽裝爬蟲程序請求的UA
  • 通過自定義請求對象,用于偽裝爬蟲程序請求的身份。
"""
基礎使用
"""
# 需求:爬取搜狗首頁的頁面數(shù)據(jù)
import urllib.request
#1.指定url
url = 'https://www.sogou.com/'

#2.發(fā)起請求:urlopen可以根據(jù)指定的url發(fā)起請求,切返回一個響應對象
response = urllib.request.urlopen(url=url)

#3.獲取頁面數(shù)據(jù):read函數(shù)返回的就是響應對象中存儲的頁面數(shù)據(jù)(byte)
page_text = response.read()

#4.持久化存儲
with open('./sougou.html','wb') as fp:
    fp.write(page_text)
    print('寫入數(shù)據(jù)成功')


"""
get:
"""
# 需求:爬取指定詞條所對應的頁面數(shù)據(jù)
import urllib.request
import urllib.parse
#指定url
url = 'https://www.sogou.com/web?query='
#url特性:url不可以存在非ASCII編碼的字符數(shù)據(jù)
word = urllib.parse.quote("人民幣")
url += word #有效的url
#發(fā)請求
response = urllib.request.urlopen(url=url)

#獲取頁面數(shù)據(jù)
page_text = response.read()

with open('renminbi.html','wb') as fp:
    fp.write(page_text)


"""
UA偽裝
"""
import urllib.request
url = 'https://www.baidu.com/'
# UA偽裝
# 1.子制定一個請求對象
headers = {
    # 存儲任意的請求頭信息
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0)
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
}
# 該請求對象的UA進行了成功的偽裝
request = urllib.request.Request(url=url, headers=headers)
# 2.針對自制定的請求對象發(fā)起請求
response = urllib.request.urlopen(request)
print(response.read())


"""
post
"""
import urllib.request
import urllib.parse
#1.指定url
url = 'https://fanyi.baidu.com/sug'
#post請求攜帶的參數(shù)進行處理  流程:
#1.將post請求參數(shù)封裝到字典
data = {
    'kw':'西瓜'
}
#2.使用parse模塊中的urlencode(返回值類型為str)進行編碼處理
data = urllib.parse.urlencode(data)
#3.將步驟2的編碼結果轉換成byte類型
data = data.encode()

#2.發(fā)起post請求:urlopen函數(shù)的data參數(shù)表示的就是經(jīng)過處理之后的post請求攜帶的參數(shù)
response = urllib.request.urlopen(url=url,data=data)

response.read()

requests模塊

  • 介紹:使用requests可以模擬瀏覽器的請求,比起之前用到的urllib,requests模塊的api更加便捷(本質就是封裝了urllib3)
  • 注意:requests庫發(fā)送請求將網(wǎng)頁內容下載下來以后,并不會執(zhí)行js代碼,這需要我們自己分析目標站點然后發(fā)起新的request請求
  • 安裝:pip3 install requests
  • 各種請求方式:常用的就是requests.get()和requests.post()
import requests
r = requests.get('https://api.github.com/events')
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
r = requests.put('http://httpbin.org/put', data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')

常見操作

"""
get請求
"""
import requests
#指定url
url = 'https://www.sogou.com/'
#發(fā)起get請求:get方法會返回請求成功的相應對象
response = requests.get(url=url)
#獲取響應中的數(shù)據(jù)值:text可以獲取響應對象中字符串形式的頁面數(shù)據(jù)
page_data = response.text
print(page_data)
#content獲取的是response對象中二進制(byte)類型的頁面數(shù)據(jù)
print(response.content)
#返回一個響應狀態(tài)碼
print(response.status_code)
#返回響應頭信息
print(response.headers)
#獲取請求的url
print(response.url)
#持久化操作
with open('./sougou.html','w',encoding='utf-8') as fp:
    fp.write(page_data)


"""
get請求帶參方式1:
"""
import requests
url = 'https://www.sogou.com/web?query=周杰倫&ie=utf-8'
response = requests.get(url=url)
page_text = response.text
with open('./zhou.html','w',encoding='utf-8') as fp:
    fp.write(page_text)

"""
get請求帶參方式2:
自定義請求頭信息
"""
# 自定義請求頭信息
import requests
url = 'https://www.sogou.com/web'
#將參數(shù)封裝到字典中
params = {
    'query':'周杰倫',
    'ie':'utf-8'
}
#自定義請求頭信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) 
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
response = requests.get(url=url,params=params,headers=headers)
response.status_code


"""
post請求
需求:登錄豆瓣網(wǎng),獲取登錄成功后的頁面數(shù)據(jù)
"""
import requests
#1.指定post請求的url
url = 'https://accounts.douban.com/login'
#封裝post請求的參數(shù)
data = {
    "source": "movie",
    "redir": "https://movie.douban.com/",
    "form_email": "15027900535",
    "form_password": "bobo@15027900535",
    "login": "登錄",
}
#自定義請求頭信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) 
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
#2.發(fā)起post請求
response = requests.post(url=url,data=data,headers=headers)
#3.獲取響應對象中的頁面數(shù)據(jù)
page_text = response.text
#4.持久化操作
with open('./douban.html','w',encoding='utf-8') as fp:
    fp.write(page_text)


"""
基于ajax的get請求
-需求:抓取豆瓣電影上電影詳情的數(shù)據(jù)
"""
import requests
url = 'https://movie.douban.com/j/chart/top_list?'
#封裝ajax的get請求中攜帶的參數(shù)
params = {
    'type':'5',
    'interval_id':'100:90',
    'action':'',
    'start':'100',
    'limit':'20'
}
#自定義請求頭信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) 
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
response = requests.get(url=url,params=params,headers=headers)
#獲取響應內容:響應內容為json串
print(response.text)



"""
基于ajax的post請求
- 需求:爬去肯德基城市餐廳位置數(shù)據(jù)
"""

import requests
#1指定url
post_url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
#處理post請求的參數(shù)
data = {
    "cname": "",
    "pid": "",
    "keyword": "上海",
    "pageIndex": "1",
    "pageSize": "10",
}
#自定義請求頭信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) 
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
#2發(fā)起基于ajax的post請求
response = requests.post(url=post_url,headers=headers,data=data)
#獲取響應內容:響應內容為json串
print(response.text)

"""
綜合項目實戰(zhàn)
- 需求:爬取搜狗知乎某一個詞條對應一定范圍頁碼表示的頁面數(shù)據(jù)
"""
# 前三頁頁面數(shù)據(jù)(1,2,3)
import requests
import os

# 創(chuàng)建一個文件夾
if not os.path.exists('./pages'):
    os.mkdir('./pages')
word = input('enter a word:')
# 動態(tài)指定頁碼的范圍
start_pageNum = int(input('enter a start pageNum:'))
end_pageNum = int(input('enter a end pageNum:'))
# 自定義請求頭信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) 
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
# 1.指定url:設計成一個具有通用的url
url = 'https://zhihu.sogou.com/zhihu'
for page in range(start_pageNum, end_pageNum + 1):
    param = {
        'query': word,
        'page': page,
        'ie': 'utf-8'
    }
    response = requests.get(url=url, params=param, headers=headers)

    # 獲取響應中的頁面數(shù)據(jù)(指定頁碼(page))
    page_text = response.text

    # 進行持久化存儲
    fileName = word + str(page) + '.html'
    filePath = 'pages/' + fileName
    with open(filePath, 'w', encoding='utf-8') as fp:
        fp.write(page_text)
        print('第%d頁數(shù)據(jù)寫入成功' % page)


"""
requests模塊高級:
- cookie:
    基于用戶的用戶數(shù)據(jù)
    - 需求:爬取張三用戶的豆瓣網(wǎng)的個人主頁頁面數(shù)據(jù)
- cookie作用:服務器端使用cookie來記錄客戶端的狀態(tài)信息。
實現(xiàn)流程:
    1.執(zhí)行登錄操作(獲取cookie)
    2.在發(fā)起個人主頁請求時,需要將cookie攜帶到該請求中
    注意:session對象:發(fā)送請求(會將cookie對象進行自動存儲)
"""
import requests

session = requests.session()
#1.發(fā)起登錄請求:將cookie獲取,且存儲到session對象中
login_url = 'https://accounts.douban.com/login'
data = {
    "source": "None",
    "redir": "https://www.douban.com/people/185687620/",
    "form_email": "15027900535",
    "form_password": "bobo@15027900535",
    "login": "登錄",
}
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) 
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
#使用session發(fā)起post請求
login_response = session.post(url=login_url,data=data,headers=headers)

#2.對個人主頁發(fā)起請求(session(cookie)),獲取響應頁面數(shù)據(jù)
url = 'https://www.douban.com/people/185687620/'
response = session.get(url=url,headers=headers)
page_text = response.text

with open('./douban110.html','w',encoding='utf-8') as fp:
    fp.write(page_text)


"""
代理操作:
- 1.代理:第三方代理本體執(zhí)行相關的事物。生活:代購,微商,中介
- 2.為什么要使用代理?
    - 反爬操作。
    - 反反爬手段
- 3.分類:
    - 正向代理:代替客戶端獲取數(shù)據(jù)
    - 反向代理:代理服務器端提供數(shù)據(jù)
- 4.免費代理ip的網(wǎng)站提供商:
    - www.goubanjia.com
    - 快代理
    - 西祠代理
- 5.代碼:
"""
import requests
url = 'http://www.baidu.com/s?ie=utf-8&wd=ip'
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) 
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
#將代理ip封裝到字典
proxy = {
    'http':'77.73.69.120:3128'
}
#更換網(wǎng)路IP
response = requests.get(url=url,proxies=proxy,headers=headers)
with open('./daili.html','w',encoding='utf-8') as fp:
    fp.write(response.text)

一、基于GET請求
  • HTTP默認的請求方法就是GET
    • 沒有請求體
    • 數(shù)據(jù)必須在1K之內!
    • GET請求數(shù)據(jù)會暴露在瀏覽器的地址欄中
  • GET請求常用的操作:
    • 在瀏覽器的地址欄中直接給出URL,那么就一定是GET請求
    • 點擊頁面上的超鏈接也一定是GET請求
    • 提交表單時,表單默認使用GET請求,但可以設置為POST
#1、基本請求
import requests
response=requests.get('http://dig.chouti.com/')
print(response.text)

#2、帶參數(shù)的GET請求->params
#2.1自己拼接GET參數(shù)
#在請求頭內將自己偽裝成瀏覽器,否則百度不會正常返回頁面內容
import requests
response=requests.get('https://www.baidu.com/s?wd=python&pn=1',
                      headers={
                        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) 
                         AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
                      })
print(response.text)


#如果查詢關鍵詞是中文或者有其他特殊符號,則不得不進行url編碼
from urllib.parse import urlencode
wd='egon老師'
encode_res=urlencode({'k':wd},encoding='utf-8')
keyword=encode_res.split('=')[1]
print(keyword)
# 然后拼接成url
url='https://www.baidu.com/s?wd=%s&pn=1' %keyword

response=requests.get(url,
                      headers={
                        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) 
                         AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
                      })
res1=response.text

#2.2params參數(shù)的使用
#上述操作可以用requests模塊的一個params參數(shù)搞定,本質還是調用urlencode
from urllib.parse import urlencode
wd='egon老師'
pn=1

response=requests.get('https://www.baidu.com/s',
                      params={
                          'wd':wd,
                          'pn':pn
                      },
                      headers={
                        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) 
                         AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
                      })
res2=response.text

#驗證結果,打開a.html與b.html頁面內容一樣
with open('a.html','w',encoding='utf-8') as f:
    f.write(res1)
with open('b.html', 'w', encoding='utf-8') as f:
    f.write(res2)

#3、帶參數(shù)的GET請求->headers
"""
#通常我們在發(fā)送請求時都需要帶上請求頭,請求頭是將自身偽裝成瀏覽器的關鍵,常見的有用的請求頭如下
Host
Referer #大型網(wǎng)站通常都會根據(jù)該參數(shù)判斷請求的來源
User-Agent #客戶端
Cookie #Cookie信息雖然包含在請求頭里,但requests模塊有單獨的參數(shù)來處理他,headers={}內就不要放它了
"""
#添加headers(瀏覽器會識別請求頭,不加可能會被拒絕訪問,比如訪問https://www.zhihu.com/explore)
import requests
response=requests.get('https://www.zhihu.com/explore')
response.status_code #500

#自己定制headers
headers={
    'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N)
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36',

}
respone=requests.get('https://www.zhihu.com/explore',
                     headers=headers)
print(respone.status_code) #200


#4、帶參數(shù)的GET請求->cookies
#登錄github,然后從瀏覽器中獲取cookies,以后就可以直接拿著cookie登錄了,無需輸入用戶名密碼
#用戶名:egonlin 郵箱378533872@qq.com 密碼lhf@123

import requests

Cookies={   'user_session':'wGMHFJKgDcmRIVvcA14_Wrt_3xaUyJNsBnPbYzEL6L0bHcfc',
}

response=requests.get('https://github.com/settings/emails',
             cookies=Cookies) #github對請求頭沒有什么限制,我們無需定制user-agent,對于其他網(wǎng)站可能還需要定制


print('378533872@qq.com' in response.text) #True
二、基于POST請求
  • 數(shù)據(jù)不會出現(xiàn)在地址欄中
  • 數(shù)據(jù)的大小沒有上限
  • 有請求體
  • 請求體中如果存在中文,會使用URL編碼!
  • requests.post()用法與requests.get()完全一致,特殊的是requests.post()有一個data參數(shù),用來存放請求體數(shù)據(jù)
"""
發(fā)送post請求,模擬瀏覽器的登錄行為
對于登錄來說,應該輸錯用戶名或密碼然后分析抓包流程,輸對了瀏覽器就跳轉了,就找不到包
自動登錄github(自己處理cookie信息)
"""
'''
一 目標站點分析
    瀏覽器輸入https://github.com/login
    然后輸入錯誤的賬號密碼,抓包
    發(fā)現(xiàn)登錄行為是post提交到:https://github.com/session
    而且請求頭包含cookie
    而且請求體包含:
        commit:Sign in
        utf8:...
        authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ==
        login:egonlin
        password:123


二 流程分析
    先GET:https://github.com/login拿到初始cookie與authenticity_token
    返回POST:https://github.com/session, 帶上初始cookie,帶上請求體(authenticity_token,用戶名,密碼等)
    最后拿到登錄cookie

    ps:如果密碼時密文形式,則可以先輸錯賬號,輸對密碼,然后到瀏覽器中拿到加密后的密碼,github的密碼是明文
'''

import requests
import re

#第一次請求
r1=requests.get('https://github.com/login')
r1_cookie=r1.cookies.get_dict() #拿到初始cookie(未被授權)
authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #從頁面中拿到CSRF TOKEN

#第二次請求:帶著初始cookie和TOKEN發(fā)送POST請求給登錄頁面,帶上賬號密碼
data={
    'commit':'Sign in',
    'utf8':'?',
    'authenticity_token':authenticity_token,
    'login':'317828332@qq.com',
    'password':'alex3714'
}
r2=requests.post('https://github.com/session',
             data=data,
             cookies=r1_cookie
             )


login_cookie=r2.cookies.get_dict()


#第三次請求:以后的登錄,拿著login_cookie就可以,比如訪問一些個人配置
r3=requests.get('https://github.com/settings/emails',
                cookies=login_cookie)

print('317828332@qq.com' in r3.text) #True




"""
#requests.session()自動幫我們保存cookie信息

補充:
requests.post(url='xxxxxxxx',
              data={'xxx':'yyy'}) #沒有指定請求頭,#默認的請求頭:application/x-www-form-urlencoed

#如果我們自定義請求頭是application/json,并且用data傳值, 則服務端取不到值
requests.post(url='',
              data={'':1,},
              headers={
                  'content-type':'application/json'
              })


requests.post(url='',
              json={'':1,},
              ) #默認的請求頭:application/json

"""
import requests
import re

session=requests.session()
#第一次請求
r1=session.get('https://github.com/login')
authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #從頁面中拿到CSRF TOKEN

#第二次請求
data={
    'commit':'Sign in',
    'utf8':'?',
    'authenticity_token':authenticity_token,
    'login':'317828332@qq.com',
    'password':'alex3714'
}
r2=session.post('https://github.com/session',
             data=data,
             )

#第三次請求
r3=session.get('https://github.com/settings/emails')

print('317828332@qq.com' in r3.text) #True
三、響應Response
#1、response屬性
import requests
respone=requests.get('http://www.itdecent.cn')
# respone屬性
print(respone.text)
print(respone.content)

print(respone.status_code)
print(respone.headers)
print(respone.cookies)
print(respone.cookies.get_dict())
print(respone.cookies.items())

print(respone.url)
print(respone.history)

print(respone.encoding)

#關閉:response.close()
from contextlib import closing
with closing(requests.get('xxx',stream=True)) as response:
    for line in response.iter_content():
    pass


#2、編碼問題
import requests
response=requests.get('http://www.autohome.com/news')
# response.encoding='gbk' #汽車之家網(wǎng)站返回的頁面內容為gb2312編碼的,而requests的默認編碼為ISO-8859-1,如果不設置成gbk則中文亂碼
print(response.text)


#3、獲取二進制數(shù)據(jù)
import requests

response=requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509868306530
&di=712e4ef3ab258b36e9f4b48e85a81c9d&imgtype=0
&src=http%3A%2F%2Fc.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F11385343fbf2b211e1fb58a1c08065380dd78e0c.jpg')

with open('a.jpg','wb') as f:
    f.write(response.content)


#3.1獲取二進制流
#stream參數(shù):一點一點的取,比如下載視頻時,如果視頻100G,用response.content然后一下子寫到文件中是不合理的

import requests

response=requests.get('https://gss3.baidu.com/6LZ0ej3k1Qd3ote6lo7D0j9wehsv/
tieba-smallvideo-transcode/1767502_56ec685f9c7ec542eeaf6eac93a65dc7_6fe25cd1347c_3.mp4',stream=True)

with open('b.mp4','wb') as f:
    for line in response.iter_content():
        f.write(line)


#4、解析json
#解析json
import requests
response=requests.get('http://httpbin.org/get')

import json
res1=json.loads(response.text) #太麻煩

res2=response.json() #直接獲取json數(shù)據(jù)

print(res1 == res2) #True

import requests
import re

#第一次請求
r1=requests.get('https://github.com/login')
r1_cookie=r1.cookies.get_dict() #拿到初始cookie(未被授權)
authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #從頁面中拿到CSRF TOKEN

#第二次請求:帶著初始cookie和TOKEN發(fā)送POST請求給登錄頁面,帶上賬號密碼
data={
    'commit':'Sign in',
    'utf8':'?',
    'authenticity_token':authenticity_token,
    'login':'317828332@qq.com',
    'password':'alex3714'
}



#測試一:沒有指定allow_redirects=False,則響應頭中出現(xiàn)Location就跳轉到新頁面,r2代表新頁面的response
r2=requests.post('https://github.com/session',
             data=data,
             cookies=r1_cookie
             )

print(r2.status_code) #200
print(r2.url) #看到的是跳轉后的頁面
print(r2.history) #看到的是跳轉前的response
print(r2.history[0].text) #看到的是跳轉前的response.text


#測試二:指定allow_redirects=False,則響應頭中即便出現(xiàn)Location也不會跳轉到新頁面,r2代表的仍然是老頁面的response
r2=requests.post('https://github.com/session',
             data=data,
             cookies=r1_cookie,
             allow_redirects=False
             )


print(r2.status_code) #302
print(r2.url) #看到的是跳轉前的頁面https://github.com/session
print(r2.history) #[]

利用github登錄后跳轉到主頁面的例子來驗證它
四、高級用法
#1、SSL Cert Verification

#證書驗證(大部分網(wǎng)站都是https)
import requests
respone=requests.get('https://www.12306.cn') #如果是ssl請求,首先檢查證書是否合法,不合法則報錯,程序終端


#改進1:去掉報錯,但是會報警告
import requests
respone=requests.get('https://www.12306.cn',verify=False) #不驗證證書,報警告,返回200
print(respone.status_code)


#改進2:去掉報錯,并且去掉警報信息
import requests
from requests.packages import urllib3
urllib3.disable_warnings() #關閉警告
respone=requests.get('https://www.12306.cn',verify=False)
print(respone.status_code)

#改進3:加上證書
#很多網(wǎng)站都是https,但是不用證書也可以訪問,大多數(shù)情況都是可以攜帶也可以不攜帶證書
#知乎\百度等都是可帶可不帶
#有硬性要求的,則必須帶,比如對于定向的用戶,拿到證書后才有權限訪問某個特定網(wǎng)站
import requests
respone=requests.get('https://www.12306.cn',
                     cert=('/path/server.crt',
                           '/path/key'))
print(respone.status_code)


#2、使用代理
#官網(wǎng)鏈接: http://docs.python-requests.org/en/master/user/advanced/#proxies

#代理設置:先發(fā)送請求給代理,然后由代理幫忙發(fā)送(封ip是常見的事情)
import requests
proxies={
    'http':'http://egon:123@localhost:9743',#帶用戶名密碼的代理,@符號前是用戶名與密碼
    'http':'http://localhost:9743',
    'https':'https://localhost:9743',
}
respone=requests.get('https://www.12306.cn',
                     proxies=proxies)

print(respone.status_code)



#支持socks代理,安裝:pip install requests[socks]
import requests
proxies = {
    'http': 'socks5://user:pass@host:port',
    'https': 'socks5://user:pass@host:port'
}
respone=requests.get('https://www.12306.cn',
                     proxies=proxies)

print(respone.status_code)


#3、超時設置
#超時設置
#兩種超時:float or tuple
#timeout=0.1 #代表接收數(shù)據(jù)的超時時間
#timeout=(0.1,0.2)#0.1代表鏈接超時  0.2代表接收數(shù)據(jù)的超時時間

import requests
respone=requests.get('https://www.baidu.com',
                     timeout=0.0001)


#4、 認證設置

#官網(wǎng)鏈接:http://docs.python-requests.org/en/master/user/authentication/

#認證設置:登陸網(wǎng)站是,彈出一個框,要求你輸入用戶名密碼(與alter很類似),此時是無法獲取html的
# 但本質原理是拼接成請求頭發(fā)送
#         r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
# 一般的網(wǎng)站都不用默認的加密方式,都是自己寫
# 那么我們就需要按照網(wǎng)站的加密方式,自己寫一個類似于_basic_auth_str的方法
# 得到加密字符串后添加到請求頭
#         r.headers['Authorization'] =func('.....')

#看一看默認的加密方式吧,通常網(wǎng)站都不會用默認的加密設置
import requests
from requests.auth import HTTPBasicAuth
r=requests.get('xxx',auth=HTTPBasicAuth('user','password'))
print(r.status_code)

#HTTPBasicAuth可以簡寫為如下格式
import requests
r=requests.get('xxx',auth=('user','password'))
print(r.status_code)

#5、異常處理

#異常處理
import requests
from requests.exceptions import * #可以查看requests.exceptions獲取異常類型

try:
    r=requests.get('http://www.baidu.com',timeout=0.00001)
except ReadTimeout:
    print('===:')
# except ConnectionError: #網(wǎng)絡不通
#     print('-----')
# except Timeout:
#     print('aaaaa')

except RequestException:
    print('Error')


#6、上傳文件
import requests
files={'file':open('a.jpg','rb')}
respone=requests.post('http://httpbin.org/post',files=files)
print(respone.status_code)
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容