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

python爬蟲之requests庫的使用詳解

 更新時(shí)間:2021年11月18日 09:47:41   作者:liver100day  
這篇文章主要為大家介紹了python爬蟲之requests庫的使用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

python爬蟲—requests庫的用法

requests是python實(shí)現(xiàn)的簡(jiǎn)單易用的HTTP庫,使用起來比urllib簡(jiǎn)潔很多,requests 允許你發(fā)送 HTTP/1.1 請(qǐng)求。指定 URL并添加查詢url字符串即可開始爬取網(wǎng)頁信息等操作

因?yàn)槭堑谌綆?,所以使用前需要cmd安裝

pip install requests

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

基本用法:

requests.get()用于請(qǐng)求目標(biāo)網(wǎng)站,類型是一個(gè)HTTPresponse類型

import requests
response = requests.get('http://www.baidu.com')
print(response.status_code)  # 打印狀態(tài)碼
print(response.url)          # 打印請(qǐng)求url
print(response.headers)      # 打印頭信息
print(response.cookies)      # 打印cookie信息
print(response.text)  #以文本形式打印網(wǎng)頁源碼
print(response.content) #以字節(jié)流形式打印

以打印狀態(tài)碼為例,運(yùn)行結(jié)果:

在這里插入圖片描述

狀態(tài)碼:200,證明請(qǐng)求目標(biāo)網(wǎng)站正常

若狀態(tài)碼為403一般是目標(biāo)存有防火墻,觸發(fā)了反爬策略被限制了IP

各種請(qǐng)求方式:

import requests
requests.get('http://www.baidu.com')
requests.post('http://www.baidu.com')
requests.put('http://www.baidu.com')
requests.delete('http://www.baidu.com')
requests.head('http://www.baidu.com')
requests.options('http://www.baidu.com')

基本的get請(qǐng)求

import requests
response = requests.get('http://www.baidu.com')
print(response.text)

在這里插入圖片描述

帶參數(shù)的GET請(qǐng)求:

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

import requests
response = requests.get("https://www.crrcgo.cc/admin/crr_supplier.html?params=1")
print(response.text)

在這里插入圖片描述

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

import requests
data = {
    'params': '1',
}
response = requests.get('https://www.crrcgo.cc/admin/crr_supplier.html?', params=data)
print(response.text)

在這里插入圖片描述

基本POST請(qǐng)求:

import requests
response = requests.post('http://baidu.com')

在這里插入圖片描述

解析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()))

在這里插入圖片描述

簡(jiǎn)單保存一個(gè)二進(jìn)制文件

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)

為你的請(qǐng)求添加頭信息

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)

此方法可以有效地避開防火墻的檢測(cè),隱藏自己身份

使用代理

同添加headers方法一樣,代理參數(shù)也是一個(gè)dict這里使用requests庫爬取了IP代理網(wǎng)站的IP與端口和類型。因?yàn)槭敲赓M(fèi)的,使用的代理地址很快就失效了。

復(fù)制代碼

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.baidu.com'
    get_ipport(get_html(url))

獲取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)

在這里插入圖片描述

會(huì)話維持

import requests
session = requests.Session()
session.get('https://www.crrcgo.cc/admin/crr_supplier.html')
response = session.get('https://www.crrcgo.cc/admin/')
print(response.text)

證書驗(yàn)證設(shè)置

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

超時(shí)異常捕獲

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)

異常處理

使用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)注腳本之家的更多內(nèi)容!

相關(guān)文章

  • python中的變量如何開辟內(nèi)存

    python中的變量如何開辟內(nèi)存

    python中的變量如何開辟內(nèi)存?今天小編就為大家介紹一下python中變量開辟內(nèi)存的方法。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • Python3 集合set入門基礎(chǔ)

    Python3 集合set入門基礎(chǔ)

    集合也也也也是python內(nèi)置的一種數(shù)據(jù)結(jié)構(gòu),它是一個(gè)無序且元素不重復(fù)的序列。這里有兩個(gè)關(guān)鍵詞一個(gè)是無序,這一點(diǎn)和字典是一樣的,另一個(gè)關(guān)鍵詞是元素不重復(fù),這一點(diǎn)和字典的key(鍵)是一樣的
    2020-02-02
  • python的即時(shí)標(biāo)記項(xiàng)目練習(xí)筆記

    python的即時(shí)標(biāo)記項(xiàng)目練習(xí)筆記

    這篇文章主要介紹了python的即時(shí)標(biāo)記項(xiàng)目練習(xí)筆記,本文是閱讀《python基礎(chǔ)教程》一書的動(dòng)手實(shí)踐項(xiàng)目,需要的朋友可以參考下
    2014-09-09
  • Pandas對(duì)DataFrame單列/多列進(jìn)行運(yùn)算(map, apply, transform, agg)

    Pandas對(duì)DataFrame單列/多列進(jìn)行運(yùn)算(map, apply, transform, agg)

    這篇文章主要介紹了Pandas對(duì)DataFrame單列/多列進(jìn)行運(yùn)算(map, apply, transform, agg),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • Python中xrange與yield的用法實(shí)例分析

    Python中xrange與yield的用法實(shí)例分析

    這篇文章主要介紹了Python中xrange與yield的用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了range和xrange功能、使用方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2017-12-12
  • Python實(shí)現(xiàn)批量上傳本地maven庫到nexus

    Python實(shí)現(xiàn)批量上傳本地maven庫到nexus

    這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)批量上傳本地maven庫到nexus,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的小伙伴可以參考下
    2024-01-01
  • Keras中Conv1D的使用及說明

    Keras中Conv1D的使用及說明

    這篇文章主要介紹了Keras中Conv1D的使用及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • 如何利用Python模擬GitHub登錄詳解

    如何利用Python模擬GitHub登錄詳解

    這篇文章主要給大家介紹了關(guān)于如何利用Python模擬GitHub登錄的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • Django crontab定時(shí)任務(wù)模塊操作方法解析

    Django crontab定時(shí)任務(wù)模塊操作方法解析

    這篇文章主要介紹了Django crontab定時(shí)任務(wù)模塊操作方法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-09-09
  • python print出共軛復(fù)數(shù)的方法詳解

    python print出共軛復(fù)數(shù)的方法詳解

    在本篇內(nèi)容里小編給大家分享的是關(guān)于python print出共軛復(fù)數(shù)的方法總結(jié)內(nèi)容,有需要的讀者們可以學(xué)習(xí)下。
    2019-06-06

最新評(píng)論