2016-10-08 63 views
0

我想在Python中使用urllib和BeautifulSoup製作webscraper。我的筆記本電腦適用於Debian,所以我不使用最新版本的urllib。BeautifulSoup的屬性錯誤獲取方法

我的目標很簡單:從維基百科表中提取數值like this one

於是,我開始了我的腳本:

import urllib 
from bs4 import BeautifulSoup 

start ="https://fr.wikipedia.org/wiki/Liste_des_monuments_historiques_de_Strasbourg" 
url = urllib.urlopen(start).read() 
bsObj = BeautifulSoup(url) 

table = bsObj.find("table", {"class":"wikitable sortable"}) 
lines = table.findAll("tr") 

然後,我用一個for循環從維基百科表的每一行廢具體數值

for line in lines: 
    longitude = line.find("data", {"class":"p-longitude"}) 
    print(longitude) 
    latitude = line.find("data", {"class":"p-latitude"}) 
    print(latitude) 

這給了例如:

<data class="p-longitude" value="7.764953">7° 45′ 54″ Est</data> 
<data class="p-latitude" value="48.588848">48° 35′ 20″ Nord</data> 

我認爲get()方法會正常工作,如:

longitude = line.find("data", {"class":"p-longitude"}).get("value") 
print(longitude) 

但我的終端打印此錯誤:

Traceback (most recent call last): 
    File "scraper_monu_historiques_wikipedia.py", line 14, in <module> 
longitude = line.find("data", {"class":"p-longitude"}).get("value") 
AttributeError: 'NoneType' object has no attribute 'get' 

我不明白爲什麼,因爲我的變量緯度和經度BeautifulSoup標籤(我用的類型()檢查),所以獲取梅索德應該工作...

如果您有解決方案,請提前致謝!

回答

3

在這個循環中:

for line in lines: 
    longitude = line.find("data", {"class":"p-longitude"}) 
    print(longitude) 
    latitude = line.find("data", {"class":"p-latitude"}) 
    print(latitude) 

對於一些線路,longitudelatitude被發現,但對別人都沒有找到,所以它們被設置爲None。在執行任何進一步的操作之前,您必須檢查它是否被找到,例如:

for line in lines: 
    longitude = line.find("data", {"class":"p-longitude"}) 
    latitude = line.find("data", {"class":"p-latitude"}) 
    if longitude and latitude: 
     longitude_value = longitude.get('value') 
     latitude_value = latitude.get('value') 
     print(longitude_value, latitude_value) 
+0

它工作正常!非常感謝你;-)! – Raphadasilva

相關問題