Requests库网络爬虫实战
實(shí)例一:頁面的爬取
>>> import requests
>>> r= requests.get("https://item.jd.com/100003717483.html")
>>> r.status_code
200
>>> r.encoding#說明從HTTP的頭部分,已經(jīng)可以解析出這個(gè)頁面的編碼信息,京東網(wǎng)站提供了頁面信息的相關(guān)編碼
'gbk'
>>> r.text[:1000]
'<!DOCTYPE HTML>\n<html lang="zh-CN">\n<head>\n <!-- shouji -->\n <meta http-equiv="Content-Type" content="text/html; charset=gbk" />\n <title>【華為nova 5 Pro】華為 HUAWEI nova 5 Pro 前置3200萬人像超級(jí)夜景4800萬AI四攝麒麟980芯片8GB+128GB綺境森林全網(wǎng)通雙4G手機(jī)【行情 報(bào)價(jià) 價(jià)格 評(píng)測(cè)】-京 東</title>\n <meta name="keywords" content="HUAWEInova 5 Pro,華為nova 5 Pro,華為nova 5 Pro報(bào)價(jià),HUAWEInova 5 Pro報(bào)價(jià)"/>\n <meta name="description" content="【華為nova 5 Pro】京東JD.COM提供華為nova 5 Pro正品行貨,并包 括HUAWEInova 5 Pro網(wǎng)購指南,以及華為nova 5 Pro圖片、nova 5 Pro參數(shù)、nova 5 Pro評(píng)論、nova 5 Pro心得、nova 5 Pro技巧等信息,網(wǎng)購華為nova 5 Pro上京東, 放心又輕松" />\n <meta name="format-detection" content="telephone=no">\n <meta http-equiv="mobile-agent" content="format=xhtml; url=//item.m.jd.com/product/100003717483.html">\n <meta http-equiv="mobile-agent" content="format=html5; url=//item.m.jd.com/product/100003717483.html">\n <meta http-equiv="X-UA-Compatible" content="IE=Edge">\n <link rel="canonical" href="//item.jd.com/100003717483.html"/>\n <link rel="dns-prefetch" href="//m'
實(shí)例二:頁面的爬取
通過headers字段讓代碼模擬瀏覽器向亞馬遜服務(wù)器提供HTTP請(qǐng)求
>>> r=requests.get("https://www.amazon.cn/gp/product/B01M8L5Z3Y")
>>> r.status_code
200
>>> r.request.headers#requests庫的response對(duì)象包含request請(qǐng)求,可以通過r.request.headers查看發(fā)給亞馬遜的request信息的頭部到底是什么內(nèi)容
{'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
'User-Agent': 'python-requests/2.18.4'說明我們的爬蟲真實(shí)的告訴了亞馬遜服務(wù)器這次訪問是由python的request庫的一個(gè)程序產(chǎn)生的,如果亞馬遜提供了這樣的來源審查,就會(huì)使這樣的訪問變得錯(cuò)誤或者不支持這樣的訪問
更改頭部信息,模擬瀏覽器向亞馬遜發(fā)送請(qǐng)求
kv={'user-agent':'Mozilla/5.0'}#重新定義了user-agent的內(nèi)容,使他等于Mozilla/5.0;Mozilla/5.0說明這時(shí)候的user-agent可能是個(gè)瀏覽器,可能是火狐,可能是Mozilla,可能是IE10的瀏覽器,Mozilla/5.0是一個(gè)很標(biāo)準(zhǔn)的瀏覽器的身份標(biāo)識(shí)的字段
>>> url='https://www.amazon.cn/gp/product/B01M8L5Z3Y'
>>> r=requests.get(url,headers=kv)
>>> r.status_code
200
>>> r.request.headers
{'user-agent': 'Mozilla/5.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
>>> r.text[:1000]
'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n\n\n\n\n\n\n\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n <!doctype html><html class="a-no-js" data-19ax5a9jf="dingo">\n <head>\n<script type="text/javascript">var ue_t0=ue_t0||+new Date();</script>\n<script type="text/javascript">\nwindow.ue_ihb = (window.ue_ihb || window.ueinit || 0) + 1;\nif (window.ue_ihb === 1) {\nvar ue_hob=+new Date();\nvar ue_id=\'WX4VYSQZVENKQC62DC82\',\nue_csm = window,\nue_err_chan = \'jserr-rw\',\nue = {};\n(function(d){var e=d.ue=d.ue||{},f=Date.now||function(){return+new Date};e.d=function(b){return f()-(b?0:d.ue_t0)};e.stub=function(b,a){if(!b[a]){var c=[];b[a]=function(){c.push([c.slice.call(arguments),e.d(),d.ue_id])};b[a].replay=function(b){for(var a;a=c.shift();)b(a[0],a[1],a[2])};b[a].isStub=1}};e.exec=function(b,a){return function(){if(1==window.ueinit)try{return b.apply(this,arguments)}catch(c){ueLogError(c,{attribution:a||"undefined",logLevel:"WARN"})}}}})(ue_csm);\n\nue.stub(ue,"'
實(shí)例三:百度搜索關(guān)鍵詞提交
>>> kv ={'wd':'python'}
>>> r = requests.get('http://www.baidu.com/s',params = kv)
>>> r.status_code
200
>>> r.request.url #提交的請(qǐng)求到底是什么,可以使用response對(duì)象中包含的request對(duì)象信息
'http://www.baidu.com/s?wd=python'
>>> len(r.text)
482773
實(shí)例四:網(wǎng)絡(luò)圖片的爬取和存儲(chǔ)
>>> path = "E:/test_test_test/abc.jpg"#圖片保存在本機(jī)的什么位置以及叫什么名字,名字后期會(huì)做處理
>>> url = "http://testpic.baojia.com/upfiles/pic/companylogo/2019/0509/aYrBoQZbVGp0DFsEq.jpg"
>>> r = requests.get(url)
>>> r.status_code
200
>>> with open(path,'wb') as f:#打開一個(gè)文件,文件是要存儲(chǔ)的abc.jpg,并且把它定義為一個(gè)文件標(biāo)識(shí)符f
... f.write(r.content)#然后把返回的內(nèi)容寫到這個(gè)文件中,r.content表示返回內(nèi)容的二進(jìn)制形式
...
96803
>>> f.close()
用圖片原來的名字存儲(chǔ)在本地
圖片爬取全代碼
>>> import requests
>>> import os
>>> url='http://testpic.baojia.com/upfiles/pic/companylogo/2019/0509/aYrBoQZbVGp0DFsEq.jpg'
>>> root = 'E://test_test_test//'#定義根目錄
>>> path = root + url.split('/')[-1]#文件路徑,url.split('/')[-1]截取url后面的圖片名字
>>> print(path)
E://test_test_test//aYrBoQZbVGp0DFsEq.jpg
>>> try:
... if not os.path.exists(root):#當(dāng)前根目錄是否存在
... os.mkdir(root)#不存在創(chuàng)建
... if not os.path.exists(path):#文件是否存在
... r = requests.get(url)#不存在,通過requests.get方式從網(wǎng)絡(luò)獲取相關(guān)文件
... with open(path,'wb') as f:
... f.write(r.content)
... f.close()
... print("文件保存成功")
... else:
... print("文件已存在")
... except:
... print("爬取失敗")
...
96803
文件保存成功
實(shí)例五:IP地址歸屬地的自動(dòng)查詢
對(duì)于一些網(wǎng)站怎么人工的分析接口并利用接口
>>> url='http://m.ip138.com/ip.asp?ip='
>>> r = requests.get(url+'202.204.80.112')
>>> r.status_code
200
>>> r.text[-500:]
'value="查詢" class="form-btn" />\r\n\t\t\t\t\t</form>\r\n\t\t\t\t</div>\r\n\t\t\t\t<div class="query-hd">ip138.com IP查詢(搜索IP地址的地理位置)</div>\r\n\t\t\t\t<h1 class="query">您查詢的IP:202.204.80.112</h1><p class="result">本站主數(shù)據(jù):北京市海淀區(qū) 北京理工大學(xué) 教育網(wǎng)</p><p class="result">參考數(shù)據(jù)一:北京市 北京理工大學(xué)</p>\r\n\r\n\t\t\t</div>\r\n\t\t</div>\r\n\r\n\t\t<div class="footer">\r\n\t\t\t<a href="http://www.miitbeian.gov.cn/" rel="nofollow" target="_blank">滬ICP備10013467號(hào)-1</a>\r\n\t\t</div>\r\n\t</div>\r\n\r\n\t<script type="text/javascript" src="/script/common.js"></script></body>\r\n</html>\r\n'
?
轉(zhuǎn)載于:https://www.cnblogs.com/suitcases/p/11200200.html
總結(jié)
以上是生活随笔為你收集整理的Requests库网络爬虫实战的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Mule ESB与Groovy编排R
- 下一篇: 动态提示的下拉框