国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術(shù)文章
文章詳情頁

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

瀏覽:48日期:2022-07-09 15:56:07

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

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

pip install requests

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

基本用法:

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) # 打印請求urlprint(response.headers) # 打印頭信息print(response.cookies) # 打印cookie信息print(response.text) #以文本形式打印網(wǎng)頁源碼print(response.content) #以字節(jié)流形式打印

運行結(jié)果:

狀態(tài)碼:200

url:www.baidu.com

headers信息

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

各種請求方式:

import requestsrequests.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 requestsresponse = requests.get(’http://httpbin.org/get’)print(response.text)

結(jié)果

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

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

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

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

結(jié)果

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

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

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

結(jié)果同上

解析json

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

結(jié)果

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

簡單保存一個二進制文件

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

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

為你的請求添加頭信息

import requestsheads = {}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代理網(wǎng)站的IP與端口和類型

因為是免費的,使用的代理地址很快就失效了。

import requestsimport redef 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 htmldef 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))

結(jié)果:

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

基本POST請求:

import requestsdata = {’name’:’tom’,’age’:’22’}response = requests.post(’http://httpbin.org/post’, data=data)

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

獲取cookie

#獲取cookieimport requestsresponse = requests.get(’http://www.baidu.com’)print(response.cookies)print(type(response.cookies))for k,v in response.cookies.items(): print(k+’:’+v)

結(jié)果:

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

會話維持

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

結(jié)果:

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

證書驗證設(shè)置

import requestsfrom requests.packages import urllib3urllib3.disable_warnings() #從urllib3中消除警告response = requests.get(’https://www.12306.cn’,verify=False) #證書驗證設(shè)為FALSEprint(response.status_code)打印結(jié)果:200

超時異常捕獲

import requestsfrom requests.exceptions import ReadTimeouttry: res = requests.get(’http://httpbin.org’, timeout=0.1) print(res.status_code)except ReadTimeout: print(timeout)

異常處理

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

所有的requests exception:

Exceptions

import requestsfrom requests.exceptions import ReadTimeout,HTTPError,RequestExceptiontry: 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 requestsimport parselimport csvf = 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()

到此這篇關(guān)于python爬蟲---requests庫的用法詳解的文章就介紹到這了,更多相關(guān)python requests庫內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 日本高清aⅴ毛片免费 | 99视频精品免费99在线 | 粉嫩jk制服美女啪啪 | 黄色美女视频网站 | 欧美精品束缚一区二区三区 | 真正全免费视频a毛片 | 精品国产杨幂在线观看福利 | 国产性自爱拍偷在在线播放 | 在线欧美精品二区三区 | 欧美大尺度免费一级特黄 | 日本乱人伦片中文字幕三区 | 中国大陆一级毛片 | 女子张开腿让男人桶视频 | 日韩精品免费一区二区三区 | 性色综合 | 在线私拍国产福利精品 | 亚洲精品推荐 | 成人久久伊人精品伊人 | 亚洲一区二区三区成人 | 狠狠色丁香婷婷综合 | 中国一级淫片aaa毛片毛片 | 久久久久久久久综合 | 综合网站 | 中国三级网站 | 久久久亚洲欧美综合 | 国产成人精品福利网站人 | 午夜手机看片 | 亚洲精品第一国产综合野 | 欧美aaa大片| 国产精品色内内在线播放 | 自拍偷拍视频在线观看 | 曰本一区| 欧美一级视屏 | 激情欧美一区二区三区 | 美女视频黄色在线观看 | 国内真实愉拍系列情侣 | 国产视频久久久久 | 免费国产不卡午夜福在线 | 在线免费亚洲 | 狠狠色综合久久婷婷 | 久久精品一区二区三区不卡牛牛 |