使用美汤在表格的第二列中打印文本



我写了这段代码来从这个页面的表格中检索文本。当我将其用于第一列时,它工作正常:

from bs4 import BeautifulSoup
import urllib2 #xbmc, xbmcgui, xbmcaddon
url = 'http://racing4everyone.eu/formula-e-201516/'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read(), 'html.parser')
for row in soup.findAll('table')[0].tbody.findAll('tr'):
    first_column = row.findAll('th')[0].text
    print first_column

但是,当我尝试从第二列中提取相同的数据时:

for row in soup.findAll('table')[0].tbody.findAll('tr'):
    second_column = row.findAll('th')[1].text
    print second_column

我收到一个错误:

ePrix
Traceback (most recent call last):
  File "addon.py", line 9, in <module>
    second_column = row.findAll('th')[1].text
IndexError: list index out of range

我做错了什么?

这是因为除第一行之外的所有行都包含单个th元素:

<tr>
<th>1</th>
<td>...</td>
...
<td>24 October 2015</td>
</tr>

您需要从每一行中找到所有tdth元素并获取第一个元素:

for row in soup.find_all('table')[0].tbody.find_all('tr')[1:]:
    print(row.find_all('td')[0].text)

[1:]这里跳过第一个标题行。

指纹:

Beijing ePrix
Putrajaya ePrix
Punta del Este ePrix
Buenos Aires ePrix
Mexico
Long Beach ePrix
Paris ePrix
Berlin ePrix
Moscow ePrix
London ePrix Race 1
London ePrix Race 2

最新更新