Python用requests庫爬取返回為空的解決辦法
首先介紹一下我們用360搜索派取城市排名前20。
我們爬取的網(wǎng)址:https://baike.so.com/doc/24368318-25185095.html
我們要爬取的內(nèi)容:

html字段:

robots協(xié)議:

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

import requests
r = requests.get("https://baike.so.com/doc/24368318-25185095.html")
r.status_code
r.text
結(jié)果分析,我們可以成功訪問到該網(wǎng)頁,但是得不到網(wǎng)頁的結(jié)果。被360搜索識別,我們將headers修改。

輸出有個小插曲,網(wǎng)頁內(nèi)容很多,我是想將前500個字符輸出,第一次格式錯了
import requests
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.status_code
r.text
接著我們對需要的內(nèi)容進行爬取,用(.find)方法找到我們內(nèi)容位置,用(.children)下行遍歷的方法對內(nèi)容進行爬取,用(isinstance)方法對內(nèi)容進行篩選:
import requests
from bs4 import BeautifulSoup
import bs4
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.status_code
r.encoding = r.apparent_encoding
soup = 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列表來存取所有城市的排名,將前20個輸出代碼如下:
import requests
from bs4 import BeautifulSoup
import bs4
Clist = 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])
最終結(jié)果:

到此這篇關(guān)于Python用requests庫爬取返回為空的解決辦法的文章就介紹到這了,更多相關(guān)Python requests返回為空內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談Python編程中3個常用的數(shù)據(jù)結(jié)構(gòu)和算法
這篇文章主要介紹了淺談Python編程中3個常用的數(shù)據(jù)結(jié)構(gòu)和算法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
Python3調(diào)用百度AI識別圖片中的文字功能示例【測試可用】
這篇文章主要介紹了Python3調(diào)用百度AI識別圖片中的文字功能,結(jié)合實例形式分析了Python3安裝及使用百度AI接口的相關(guān)操作技巧,并附帶說明了百度官方AI平臺的注冊及接口調(diào)用操作方法,需要的朋友可以參考下2019-03-03
sklearn-SVC實現(xiàn)與類參數(shù)詳解
今天小編就為大家分享一篇sklearn-SVC實現(xiàn)與類參數(shù)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python壓縮模塊zipfile實現(xiàn)原理及用法解析
這篇文章主要介紹了Python壓縮模塊zipfile實現(xiàn)原理及用法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08

