2017-03-03 54 views
0

我是Python的新手,我想從表中獲取「價格」數據列,但是我無法檢索該數據。從Python和美麗的湯表獲取列

目前我在做什麼:

# Libraies 
from urllib.request import urlopen 
from bs4 import BeautifulSoup 

html = urlopen("http://pythonscraping.com/pages/page3.html") 
soup = BeautifulSoup(html, "html.parser") 
table = soup.find("table") 

for row in table.find_all("tr"): 

    col = row.find_all("td") 

    print(col[2]) 
    print("---") 

我不斷收到一個列表索引值範圍。我已經閱讀了文檔並嘗試了幾種不同的方式,但我似乎無法理解它。

此外,我正在使用Python3。

回答

0

的問題是,你遍歷所有tr在表內,有一個標題tr在你不需要的開始,所以只是避免使用那個:

# Libraies 
from urllib.request import urlopen 
from bs4 import BeautifulSoup 

html = urlopen("http://pythonscraping.com/pages/page3.html") 
soup = BeautifulSoup(html, "html.parser") 
table = soup.find("table") 

for row in table.find_all("tr")[1:]: 

    col = row.find_all("td") 

    print(col[2]) 
    print("---") 
+0

這是問題。我會確保下次檢查表格結構。 – liquidsword92

0

可能意味着其中一行沒有td標記。你可以換的col[2]print或任何使用在try except塊,而忽略情況下col爲空或少於三個項目

for row in table.find_all("tr"): 

    col = row.find_all("td") 
    try: 
     print(col[2]) 
     print("---") 
    except IndexError: 
     pass