2017-10-10 228 views
0

我是一個編寫網絡爬蟲的新手。我想使用http://www.creditchina.gov.cn/search_all#keyword=&searchtype=0&templateId=&creditType=&areas=&objectType=2&page=1的搜索引擎來檢查我的輸入是否有效。BeautifulSoup獲取標籤之間沒有任何東西

例如,912101127157655762是有效輸入,912101127157655760無效。

觀察從開發工具網站的源代碼後,我發現,如果輸入的是無效號碼,標籤是: enter image description here

而如果輸入的是有效的,標籤將是:

enter image description here 因此,我想通過檢查'ul class =「credit-info-results public-results-left item-template」'標籤中是否有任何內容來確定輸入是否有效。這裏是我寫我的網絡爬蟲的:

import urllib 
from bs4 import BeautifulSoup 
url = 'http://www.creditchina.gov.cn/search_all#keyword=912101127157655762&searchtype=0& 
templateId=&creditType=&areas=&objectType=2&page=1' 
req = urllib.request.Request(url) 
data = urllib.request.urlopen(req) 
bs = data.read().decode('utf-8') 
soup = BeautifulSoup(bs, 'lxml') 
check = soup.find_all("ul", {"class": "credit-info-results public-results-left item-template"}) 
if check == []: 
    # TODO 
if check != []: 
    # TODO 

但是,check的值總是[]。我無法理解爲什麼選項卡之間沒有任何內容。希望有人可以幫我解決問題。

回答

0

你沒有html,但JS對象作爲響應。這就是BS無法解析它的原因。

您可以使用子字符串搜索來檢查響應是否包含某些內容。

import urllib 
from bs4 import BeautifulSoup 
url = 'http://www.creditchina.gov.cn/search_all#keyword=912101127157655762&searchtype=0& 
templateId=&creditType=&areas=&objectType=2&page=1' 
req = urllib.request.Request(url) 
data = urllib.request.urlopen(req) 
bs = data.read().decode('utf-8') 

ul_pos = bs.find('credit-info-results public-results-left item-template') 
if ul_pos <> 0: 
    bs = bs[ul_pos:] 

soup = BeautifulSoup(bs, 'lxml') 
check = soup.find_all("ul", {"class": "credit-info-results public-results-left item-template"}) 
if check == []: 
    # TODO 
if check != []: 
    # TODO 
+0

如何知道我是否得到了html而不是JS對象?此外,我檢查了bs.find('credit-info-results public-results-left item-template')的值是39202,同時輸入912101127155762和912101127157655760,它們應該返回不同的輸出值。這是令人困惑的... –

+0

我已經更新了我的答案,請嘗試一下。不幸的是,由於本網站禁止了我的請求,所以我無法自己測試。 –

+0

我發現我得到的只是網絡的一個模板。我需要看網絡而不是開發人員工具的元素。無論如何,感謝您的時間和耐心! –