编程语言
首页 > 编程语言> > python-使用beautifulsoup在表的第二列中打印文本

python-使用beautifulsoup在表的第二列中打印文本

作者:互联网

我编写了这段代码来从this页的表中检索文本.当我将其用于第一列时,它可以正常工作:

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>

您需要从每一行中找到所有的td或th元素,并获得第一个:

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

标签:python-2-7,beautifulsoup,web-scraping,python
来源: https://codeday.me/bug/20191118/2031961.html