最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python爬蟲---requests庫的用法詳解

 更新時間:2020年09月28日 21:46:07   作者:AGENTFITZ  
requests是python實現(xiàn)的簡單易用的HTTP庫,使用起來比urllib簡潔很多,這里就為大家分享一下

requests是python實現(xiàn)的簡單易用的HTTP庫,使用起來比urllib簡潔很多

因為是第三方庫,所以使用前需要cmd安裝

pip install requests

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

基本用法:

requests.get()用于請求目標網站,類型是一個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) #以文本形式打印網頁源碼
print(response.content) #以字節(jié)流形式打印

運行結果:

狀態(tài)碼:200

url:www.baidu.com

headers信息

各種請求方式:

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')

基本的get請求

import requests

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

結果

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

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

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)

結果同上

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

結果

簡單保存一個二進制文件

二進制內容為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)

為你的請求添加頭信息

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)

使用代理

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

這里使用requests庫爬取了IP代理網站的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))

結果:

基本POST請求:

import requests

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

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

獲取cookie

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

結果:

會話維持

import requests

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

結果:

證書驗證設置

import requests
from requests.packages import urllib3

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

超時異常捕獲

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)

異常處理

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

所有的requests exception:

Exceptions

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')

25行代碼帶你爬取4399小游戲數(shù)據(jù)

import requests
import parsel
import csv
f = open('4399游戲.csv', mode='a', encoding='utf-8-sig', newline='')

csv_writer = csv.DictWriter(f, fieldnames=['游戲地址', '游戲名字'])
csv_writer.writeheader()
for page in range(1, 106):
  url = 'http://www.4399.com/flash_fl/5_{}.htm'.format(page)
  headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
  }
  response = requests.get(url=url, headers=headers)
  response.encoding = response.apparent_encoding
  selector = parsel.Selector(response.text)
  lis = selector.css('#classic li')
  for li in lis:
    dit ={}
    data_url = li.css('a::attr(href)').get()
    new_url = 'http://www.4399.com' + data_url.replace('http://', '/')
    dit['游戲地址'] = new_url
    title = li.css('img::attr(alt)').get()
    dit['游戲名字'] = title
    print(new_url, title)
    csv_writer.writerow(dit)
f.close()

到此這篇關于python爬蟲---requests庫的用法詳解的文章就介紹到這了,更多相關python requests庫內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 分享一些非常實用的Python小技巧

    分享一些非常實用的Python小技巧

    這篇文章主要分享一些非常實用的Python小技巧,助力你在Python學習的道路上一帆風順,接下來就一起來學習一下吧
    2023-03-03
  • 解決pycharm不能自動補全第三方庫的函數(shù)和屬性問題

    解決pycharm不能自動補全第三方庫的函數(shù)和屬性問題

    這篇文章主要介紹了解決pycharm不能自動補全第三方庫的函數(shù)和屬性問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • numpy中幾種隨機數(shù)生成函數(shù)的用法

    numpy中幾種隨機數(shù)生成函數(shù)的用法

    numpy是Python中常用的科學計算庫,其中也包含了一些隨機數(shù)生成函數(shù),本文主要介紹了numpy中幾種隨機數(shù)生成函數(shù)的用法,具有一定的參考價值,感興趣的可以了解一下
    2023-11-11
  • Python 找出出現(xiàn)次數(shù)超過數(shù)組長度一半的元素實例

    Python 找出出現(xiàn)次數(shù)超過數(shù)組長度一半的元素實例

    這篇文章主要介紹了Python 找出出現(xiàn)次數(shù)超過數(shù)組長度一半的元素實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python中八種數(shù)據(jù)導入方法總結

    Python中八種數(shù)據(jù)導入方法總結

    數(shù)據(jù)分析過程中,需要對獲取到的數(shù)據(jù)進行分析,往往第一步就是導入數(shù)據(jù)。導入數(shù)據(jù)有很多方式,不同的數(shù)據(jù)文件需要用到不同的導入方式,相同的文件也會有幾種不同的導入方式。下面總結幾種常用的文件導入方法
    2022-11-11
  • Python利用cnocr庫實現(xiàn)pdf文件的文字識別

    Python利用cnocr庫實現(xiàn)pdf文件的文字識別

    很多pdf文件文字識別軟件都會收費,免費的網頁版可能會帶來信息泄露,所以本文為大家介紹了如何利用Python中的cnocr庫完成中文掃描pdf文件的文字識別,需要的可以參考下
    2024-12-12
  • python?datetime模塊詳解

    python?datetime模塊詳解

    Python中常用于時間的模塊有time、datetime 和 calendar,顧名思義 time 是表示時間(時、分、秒、毫秒)等,calendar 是表示日歷時間的,本章先討論 datetime 模塊,需要的朋友可以參考下
    2022-06-06
  • Python中request庫的各種用法詳細解析

    Python中request庫的各種用法詳細解析

    本文詳細介紹了Python的requests庫的安裝與使用,包括HTTP請求方法、請求頭、請求體的基本概念,以及發(fā)送GET和POST請求的基本用法,同時,探討了會話對象、處理重定向、超時設置、代理支持等高級功能,幫助讀者更高效地處理復雜的HTTP請求場景,需要的朋友可以參考下
    2024-10-10
  • 使用python檢測主機存活端口及檢查存活主機

    使用python檢測主機存活端口及檢查存活主機

    這篇文章主要介紹了使用python檢測主機存活端口及檢查存活主機的相關資料,需要的朋友可以參考下
    2015-10-10
  • 經驗豐富程序員才知道的8種高級Python技巧

    經驗豐富程序員才知道的8種高級Python技巧

    這篇文章主要介紹了經驗豐富程序員才知道的8種高級Python技巧,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07

最新評論

万荣县| 四会市| 娄底市| 西吉县| 伊川县| 东丽区| 庆阳市| 石泉县| 深泽县| 抚远县| 石台县| 青河县| 商南县| 渭南市| 桓台县| 侯马市| 平泉县| 漳浦县| 宜宾县| 黄浦区| 淮安市| 丰宁| 家居| 新泰市| 莱州市| 永寿县| 大姚县| 海晏县| 抚宁县| 满洲里市| 绥芬河市| 开远市| 铜鼓县| 那曲县| 阿勒泰市| 五华县| 吕梁市| 陈巴尔虎旗| 于都县| 治县。| 乐山市|