Python用requests庫(kù)爬取返回為空的解決辦法
首先介?一下我??用360搜索派取城市排名前20。我們爬取的網(wǎng)址:https://baike.so.com/doc/24368318-25185095.html
我們要爬取的內(nèi)容:
html字段:
robots協(xié)議:
現(xiàn)在我們開(kāi)始用python IDLE 爬取
import requestsr = requests.get('https://baike.so.com/doc/24368318-25185095.html')r.status_coder.text
結(jié)果分析,我們可以成功訪問(wèn)到該網(wǎng)頁(yè),但是得不到網(wǎng)頁(yè)的結(jié)果。被360搜索識(shí)別,我們將headers修改。
輸出有個(gè)小插曲,網(wǎng)頁(yè)內(nèi)容很多,我是想將前500個(gè)字符輸出,第一次格式錯(cuò)了
import requestsheaders = { ’Cookie’:’OCSSID=4df0bjva6j7ejussu8al3eqo03’, ’User-Agent’:’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36’ ’(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36’,}r = requests.get('https://baike.so.com/doc/24368318-25185095.html', headers = headers)r.status_coder.text
接著我們對(duì)需要的內(nèi)容進(jìn)行爬取,用(.find)方法找到我們內(nèi)容位置,用(.children)下行遍歷的方法對(duì)內(nèi)容進(jìn)行爬取,用(isinstance)方法對(duì)內(nèi)容進(jìn)行篩選:
import requestsfrom bs4 import BeautifulSoupimport bs4headers = { ’Cookie’:’OCSSID=4df0bjva6j7ejussu8al3eqo03’, ’User-Agent’:’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36’ ’(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36’,}r = requests.get('https://baike.so.com/doc/24368318-25185095.html', headers = headers)r.status_coder.encoding = r.apparent_encodingsoup = BeautifulSoup(r.text, 'html.parser')for tr in soup.find(’tbody’).children:if isinstance(tr, bs4.element.Tag):tds = tr(’td’)print([tds[0].string, tds[1].string, tds[2].string])
得到結(jié)果如下:
修改輸出的數(shù)目,我們用Clist列表來(lái)存取所有城市的排名,將前20個(gè)輸出代碼如下:
import requestsfrom bs4 import BeautifulSoupimport bs4Clist = list() #存所有城市的列表headers = { ’Cookie’:’OCSSID=4df0bjva6j7ejussu8al3eqo03’, ’User-Agent’:’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36’ ’(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36’,}r = requests.get('https://baike.so.com/doc/24368318-25185095.html', headers = headers)r.encoding = r.apparent_encoding #將html的編碼解碼為utf-8格式soup = BeautifulSoup(r.text, 'html.parser') #重新排版for tr in soup.find(’tbody’).children: #將tbody標(biāo)簽的子列全部讀取if isinstance(tr, bs4.element.Tag): #篩選tb列表,將有內(nèi)容的篩選出啦 tds = tr(’td’) Clist.append([tds[0].string, tds[1].string, tds[2].string])for i in range(21): print(Clist[i])
最終結(jié)果:
到此這篇關(guān)于Python用requests庫(kù)爬取返回為空的解決辦法的文章就介紹到這了,更多相關(guān)Python requests返回為空內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Ajax對(duì)xml信息的接收和處理操作實(shí)例分析2. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐3. Ajax返回值類型與用法實(shí)例分析4. XML入門精解之結(jié)構(gòu)與語(yǔ)法5. 如何使用CSS3畫出一個(gè)叮當(dāng)貓6. ajax處理php返回json數(shù)據(jù)例子7. Java 如何解析key為動(dòng)態(tài)的json操作8. 在python下實(shí)現(xiàn)word2vec詞向量訓(xùn)練與加載實(shí)例9. ASP如何檢測(cè)某文件夾是否存在,不存在則自動(dòng)創(chuàng)建10. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析
