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

Python爬蟲之requests庫基本介紹

 更新時間:2022年02月09日 09:58:54   作者:人猿宇宙  
大家好,本篇文章主要講的是Python爬蟲之requests庫基本介紹,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下

一、說明

requests是一個很實用的Python HTTP客戶端庫,爬蟲和測試服務(wù)器響應(yīng)數(shù)據(jù)時經(jīng)常會用到,requests是Python語言的第三方的庫,專門用于發(fā)送HTTP請求,使用起來比urllib簡潔很多。

Requests 有這些功能:

1、Keep-Alive & 連接池
2、國際化域名和 URL
3、帶持久 Cookie 的會話
4、瀏覽器式的 SSL 認(rèn)證
5、自動內(nèi)容解碼
6、基本/摘要式的身份認(rèn)證
7、優(yōu)雅的 key/value Cookie
8、自動解壓
9、Unicode 響應(yīng)體
10、HTTP(S) 代理支持
11、文件分塊上傳
12、流下載
13、連接超時
14、分塊請求
15、支持 .netrc
Requests 支持 Python 2.6—2.7以及3.3—3.7,而且能在 PyPy 下完美運行。

用pip進(jìn)行第三方庫的安裝

pip install requests

安裝完成后import一下,正常則說明可以開始使用了。

二、基本用法:

1、requests.get()

用于請求目標(biāo)網(wǎng)站,類型是一個HTTPresponse類型

import requests

response = requests.get('http://www.baidu.com')
print(response.status_code)  # 打印狀態(tài)碼
print(response.url)          # 打印請求url
print(response.headers)      # 打印頭信息
print(response.cookies)      # 打印cookie信息
print(response.text)  #以文本形式打印網(wǎng)頁源碼
print(response.content) #以字節(jié)流形式打印
print(response.content.decode("utf-8")) #解決了通過response.text直接返回顯示亂碼的問題
response.encoding="utf-8" #避免亂碼的問題發(fā)生

2、各種請求方式

import requests

requests.get('http://httpbin.org/get')
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')

3、基本的get請求

import requests

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

4、帶參數(shù)的get請求

第一種直接將參數(shù)放在url內(nèi)

import requests

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

另一種先將參數(shù)填寫在dict中,發(fā)起請求時params參數(shù)指定為dict

import requests

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

5、解析json

import requests

response = requests.get('http://httpbin.org/get')
print(response.text)
print(response.json())  #response.json()方法同json.loads(response.text)
print(type(response.json()))

如果 JSON 解碼失敗, 將會拋出 ValueError: No JSON object could be decoded 異常。而成功調(diào)用 response.json() 并不意味著響應(yīng)的成功。有的服務(wù)器會在失敗的響應(yīng)中包含一個 JSON 對象(比如 HTTP 500 的錯誤細(xì)節(jié))。這種 JSON 會被解碼返回。要檢查請求是否成功,請使用 r.raise_for_status() 或者檢查 response.status_code 是否和你的期望相同

6、保存一個二進(jìn)制文件

二進(jìn)制內(nèi)容為response.content

import requests

response = requests.get('http://img.ivsky.com/img/tupian/pre/201708/30/kekeersitao-002.jpg')
b = response.content
with open('F://fengjing.jpg','wb') as f:
    f.write(b)

7、添加heads信息

import requests
heads = {}
heads['User-Agent'] = 'Mozilla/5.0 ' \
                          '(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \
                          '(KHTML, like Gecko) Version/5.1 Safari/534.50'
 response = requests.get('http://www.baidu.com',headers=headers)

8、使用代理

同添加headers方法,代理參數(shù)也要是一個dict

這里使用requests庫爬取了IP代理網(wǎng)站的IP與端口和類型

import requests
import re

def get_html(url):
    proxy = {
        'http': '120.25.253.234:812',
        'https': '163.125.222.244:8123'
    }
    heads = {}
    heads['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'
    req = requests.get(url, headers=heads,proxies=proxy)
    html = req.text
    return html

def get_ipport(html):
    regex = r'<td data-title="IP">(.+)</td>'
    iplist = re.findall(regex, html)
    regex2 = '<td data-title="PORT">(.+)</td>'
    portlist = re.findall(regex2, html)
    regex3 = r'<td data-title="類型">(.+)</td>'
    typelist = re.findall(regex3, html)
    sumray = []
    for i in iplist:
        for p in portlist:
            for t in typelist:
                pass
            pass
        a = t+','+i + ':' + p
        sumray.append(a)
    print('高匿代理')
    print(sumray)


if __name__ == '__main__':
    url = 'http://www.kuaidaili.com/free/'
    get_ipport(get_html(url))

9、基本POST請求

import requests

data = {'name':'tom','age':'22'}

response = requests.post('http://httpbin.org/post', data=data)

10、獲取cookie

import requests

response = requests.get('http://www.baidu.com')
print(response.cookies)
print(type(response.cookies))
for k,v in response.cookies.items():
    print(k+':'+v)

11、會話維持

import requests

session = requests.Session()
session.get('http://httpbin.org/cookies/set/number/12345')
response = session.get('http://httpbin.org/cookies')
print(response.text)

11、證書驗證設(shè)置

import requests
from requests.packages import urllib3

urllib3.disable_warnings()  #從urllib3中消除警告
response = requests.get('https://www.12306.cn',verify=False)  #證書驗證設(shè)為FALSE
print(response.status_code)

12、超時異常捕獲

import requests
from requests.exceptions import ReadTimeout

try:
    res = requests.get('http://httpbin.org', timeout=0.1)
    print(res.status_code)
except ReadTimeout:
    print(timeout)

13、異常處理

在你不確定會發(fā)生什么錯誤時,盡量使用try…except來捕獲異常

import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestException

try:
    response = requests.get('http://www.baidu.com',timeout=0.5)
    print(response.status_code)
except ReadTimeout:
    print('timeout')
except HTTPError:
    print('httperror')
except RequestException:
    print('reqerror')

總結(jié)

到此這篇關(guān)于Python爬蟲之requests庫基本介紹的文章就介紹到這了,更多相關(guān)Python requests庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 基于Python實現(xiàn)簡單的漢字拼音轉(zhuǎn)換工具

    基于Python實現(xiàn)簡單的漢字拼音轉(zhuǎn)換工具

    將漢字轉(zhuǎn)為拼音,可以用于批量漢字注音、文字排序、拼音檢索文字等常見場景?,F(xiàn)在互聯(lián)網(wǎng)上有許多拼音轉(zhuǎn)換工具,基于Python的開源模塊也不少,本文將利用pypinyin模塊制作簡單的漢字拼音轉(zhuǎn)換工具,感興趣的可以了解一下
    2022-09-09
  • 詳解numpy1.19.4與python3.9版本沖突解決

    詳解numpy1.19.4與python3.9版本沖突解決

    這篇文章主要介紹了詳解numpy1.19.4與python3.9版本沖突解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • Python+Pygame實現(xiàn)之走四棋兒游戲的實現(xiàn)

    Python+Pygame實現(xiàn)之走四棋兒游戲的實現(xiàn)

    大家以前應(yīng)該都聽說過一個游戲:叫做走四棋兒。直接在家里的水泥地上用燒完的炭火灰畫出幾條線,擺上幾顆石頭子即可。當(dāng)時的火爆程度可謂是達(dá)到了一個新的高度。本文將利用Pygame實現(xiàn)這一游戲,需要的可以參考一下
    2022-07-07
  • MacOS(M1芯片 arm架構(gòu))下安裝PyTorch的詳細(xì)過程

    MacOS(M1芯片 arm架構(gòu))下安裝PyTorch的詳細(xì)過程

    這篇文章主要介紹了MacOS(M1芯片 arm架構(gòu))下安裝PyTorch的詳細(xì)過程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-02-02
  • Win10系統(tǒng)下Pytorch環(huán)境的搭建過程

    Win10系統(tǒng)下Pytorch環(huán)境的搭建過程

    今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著Win10系統(tǒng)Pytorch環(huán)境搭建過程展開,文中有非常詳細(xì)的介紹及圖文示例,需要的朋友可以參考下
    2021-06-06
  • Python實現(xiàn)獲取當(dāng)前目錄下文件名代碼詳解

    Python實現(xiàn)獲取當(dāng)前目錄下文件名代碼詳解

    這篇文章主要介紹了Python實現(xiàn)獲取當(dāng)前目錄下文件名,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • python實現(xiàn)浪漫的煙花秀

    python實現(xiàn)浪漫的煙花秀

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)浪漫的煙花秀,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • 如何在Python中導(dǎo)入EXCEL數(shù)據(jù)

    如何在Python中導(dǎo)入EXCEL數(shù)據(jù)

    這篇文章主要介紹了使用Python處理EXCEL基礎(chǔ)操作篇1,如何在Python中導(dǎo)入EXCEL數(shù)據(jù),文中提供了解決思路和部分實現(xiàn)代碼,一起來看看吧
    2023-03-03
  • 淺談五大Python Web框架

    淺談五大Python Web框架

    Python這么多框架,能挨個玩?zhèn)€遍的人不多,坦白的說我也只用過其中的三個開發(fā)過項目,另外一些稍微接觸過,所以這里只能淺談一下,歡迎懂行的朋友們補(bǔ)充
    2017-03-03
  • pytorch快速搭建神經(jīng)網(wǎng)絡(luò)_Sequential操作

    pytorch快速搭建神經(jīng)網(wǎng)絡(luò)_Sequential操作

    這篇文章主要介紹了pytorch快速搭建神經(jīng)網(wǎng)絡(luò)_Sequential操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06

最新評論