您好,登錄后才能下訂單哦!
小編給大家分享一下python爬蟲中requests庫怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
requests是python實現的簡單易用的HTTP庫,使用起來比urllib簡潔很多,requests 允許你發送 HTTP/1.1 請求。指定 URL并添加查詢url字符串即可開始爬取網頁信息等操作
因為是第三方庫,所以使用前需要cmd安裝
pip install requests
安裝完成后import一下,正常則說明可以開始使用了
基本用法:
requests.get()
用于請求目標網站,類型是一個HTTPresponse類型
import requests response = requests.get('http://www.baidu.com') print(response.status_code) # 打印狀態碼 print(response.url) # 打印請求url print(response.headers) # 打印頭信息 print(response.cookies) # 打印cookie信息 print(response.text) #以文本形式打印網頁源碼 print(response.content) #以字節流形式打印
以打印狀態碼為例,運行結果:
狀態碼:200,證明請求目標網站正常
若狀態碼為403一般是目標存有防火墻,觸發了反爬策略被限制了IP
各種請求方式:
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')
import requests response = requests.get('http://www.baidu.com') print(response.text)
第一種直接將參數放在url內
import requests response = requests.get("https://www.crrcgo.cc/admin/crr_supplier.html?params=1") print(response.text)
另一種先將參數填寫在data中,發起請求時將params參數指定為data
import requests data = { 'params': '1', } response = requests.get('https://www.crrcgo.cc/admin/crr_supplier.html?', params=data) print(response.text)
基本POST請求:
import requests response = requests.post('http://baidu.com')
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()))
簡單保存一個二進制文件
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方法一樣,代理參數也是一個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.baidu.com' get_ipport(get_html(url))
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('https://www.crrcgo.cc/admin/crr_supplier.html') response = session.get('https://www.crrcgo.cc/admin/') 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)
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')
以上是“python爬蟲中requests庫怎么用”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。