久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Python用requests庫爬取返回為空的解決辦法

瀏覽:146日期:2022-06-27 13:45:00

首先介?一下我??用360搜索派取城市排名前20。我們爬取的網(wǎng)址:https://baike.so.com/doc/24368318-25185095.html

我們要爬取的內(nèi)容:

Python用requests庫爬取返回為空的解決辦法

html字段:

Python用requests庫爬取返回為空的解決辦法

robots協(xié)議:

Python用requests庫爬取返回為空的解決辦法

現(xiàn)在我們開始用python IDLE 爬取

Python用requests庫爬取返回為空的解決辦法

import requestsr = requests.get('https://baike.so.com/doc/24368318-25185095.html')r.status_coder.text

結果分析,我們可以成功訪問到該網(wǎng)頁,但是得不到網(wǎng)頁的結果。被360搜索識別,我們將headers修改。

Python用requests庫爬取返回為空的解決辦法

輸出有個小插曲,網(wǎng)頁內(nèi)容很多,我是想將前500個字符輸出,第一次格式錯了

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

接著我們對需要的內(nèi)容進行爬取,用(.find)方法找到我們內(nèi)容位置,用(.children)下行遍歷的方法對內(nèi)容進行爬取,用(isinstance)方法對內(nèi)容進行篩選:

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

得到結果如下:

Python用requests庫爬取返回為空的解決辦法

修改輸出的數(shù)目,我們用Clist列表來存取所有城市的排名,將前20個輸出代碼如下:

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標簽的子列全部讀取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])

最終結果:

Python用requests庫爬取返回為空的解決辦法

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

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 云林县| 阿克陶县| 察隅县| 民和| 三门县| 吉隆县| 博乐市| 拜城县| 华坪县| 于田县| 新密市| 通辽市| 阿坝| 东明县| 土默特右旗| 竹山县| 怀来县| 凤庆县| 格尔木市| 东兰县| 泾川县| 桐乡市| 平果县| 滦南县| 兰考县| 嫩江县| 武冈市| 乐都县| 霸州市| 平潭县| 安化县| 柘荣县| 横峰县| 西华县| 谷城县| 沁源县| 揭阳市| 五大连池市| 政和县| 新宾| 乐山市|