Python:无法访问列表元素,即使它存在
Python : Cannot access list element even though it exists
我正在尝试使用 Python 及其 urllib2 和 BeautifulSoup 个库。
我尝试遍历所需 table 的行,然后将 "td" 中指定的每一行中的数据存储到列表变量 row_data 中。虽然我可以打印整个列表,但我无法访问特定索引处的列表,解释器会抛出 "list index out of range" 错误。这是我的代码和输出。
import urllib2
from bs4 import BeautifulSoup
link = 'http://www.babycenter.in/a25008319/most-popular-indian-baby-names-of-2013'
page = urllib2.urlopen(link)
soup = BeautifulSoup(page)
right_table = soup.find('table', class_= 'contentTable colborders')
name=[]
meaning=[]
alternate=[]
for row in right_table.find_all("tr"):
row_datas = row.find_all("td")
print row_datas
print row_datas[0]
输出:
[]Traceback (most recent call last):
File "C:\Users\forcehandler\Documents\python\data_scrape.py", line 41, in <module>
print row_datas[0]
IndexError: list index out of range
[Finished in 1.6s]
我试过类似的代码来标出任何明显的错误,但无济于事。
代码:
i = [range(y,10) for y in range(5)]
for j in i:
print j
print j[0]
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1
[2, 3, 4, 5, 6, 7, 8, 9]
2
[3, 4, 5, 6, 7, 8, 9]
3
[4, 5, 6, 7, 8, 9]
4
我是编程新手,在其他任何地方都找不到帮助。提前致谢!
编辑:Traceback 之前的“[]”可能在复制粘贴时不小心滑入了输出。并感谢您的帮助 answers/suggestions.
解决方案:我在使用数据之前没有检查数据的完整性。事实证明,第一行仅包含 'th' 个值,没有 'td' 个值,因此出现错误。
经验教训:在将数据投入使用之前始终对其进行测试。
旁注:这是我在 Whosebug 上的第一个问题,如此快速、优质和有用的回复让我不知所措。
您收到此错误是因为您的列表没有元素,row.find_all("td")
找不到任何内容,您必须检查 html 结构或使用 select
方法.
select()
return 通过 CSSS 选择器选择的所有元素,它非常强大,您的代码将是这样的:
row_datas = soup.select("td") #Note that select() is method of a BeautifulSoup Object .
print row_datas
print row_datas[0]
您的输出显示至少有一行是 空:
[]Traceback (most recent call last):
^^
[]
是一个空列表,输出是由您的 print row_datas
行产生的。通常我希望在它和 Traceback
之间有一个换行符;也许你没有正确复制你的输出,或者你有一个控制台使用大小缓冲区而不是行缓冲导致它混合 stdout 和 stderr。
那是因为第一行中有 th
header 个单元格:
>>> rows = soup.select('table.contentTable tr')
>>> rows[0].find('td') is None
True
>>> rows[0].find_all('th')
[<th width="20%">Name</th>, <th>Meaning</th>, <th>Popular <br/>\nalternate spellings</th>]
还有一个这样的行,因此您必须进行防御性编码:
>>> rows[26]
<tr><th width="20%">Name</th><th>Meaning</th><th>Popular <br/>\nalternate spellings</th></tr>
您可以只测试是否有任何带有 if
语句的元素:
if row_datas:
print row_datas[0]
提取所有名称、含义和替代拼写的代码非常简单:
for row in soup.select('table.contentTable tr'):
cells = row.find_all('td')
if not cells:
continue
name_link = cells[0].find('a')
name, link = name_link.get_text(strip=True), name_link.get('href')
meaning, alt = (cell.get_text(strip=True) for cell in cells[1:])
print '{}: {} ({})'.format(name, meaning, alt)
我正在尝试使用 Python 及其 urllib2 和 BeautifulSoup 个库。
我尝试遍历所需 table 的行,然后将 "td" 中指定的每一行中的数据存储到列表变量 row_data 中。虽然我可以打印整个列表,但我无法访问特定索引处的列表,解释器会抛出 "list index out of range" 错误。这是我的代码和输出。
import urllib2
from bs4 import BeautifulSoup
link = 'http://www.babycenter.in/a25008319/most-popular-indian-baby-names-of-2013'
page = urllib2.urlopen(link)
soup = BeautifulSoup(page)
right_table = soup.find('table', class_= 'contentTable colborders')
name=[]
meaning=[]
alternate=[]
for row in right_table.find_all("tr"):
row_datas = row.find_all("td")
print row_datas
print row_datas[0]
输出:
[]Traceback (most recent call last):
File "C:\Users\forcehandler\Documents\python\data_scrape.py", line 41, in <module>
print row_datas[0]
IndexError: list index out of range
[Finished in 1.6s]
我试过类似的代码来标出任何明显的错误,但无济于事。 代码:
i = [range(y,10) for y in range(5)]
for j in i:
print j
print j[0]
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1
[2, 3, 4, 5, 6, 7, 8, 9]
2
[3, 4, 5, 6, 7, 8, 9]
3
[4, 5, 6, 7, 8, 9]
4
我是编程新手,在其他任何地方都找不到帮助。提前致谢!
编辑:Traceback 之前的“[]”可能在复制粘贴时不小心滑入了输出。并感谢您的帮助 answers/suggestions.
解决方案:我在使用数据之前没有检查数据的完整性。事实证明,第一行仅包含 'th' 个值,没有 'td' 个值,因此出现错误。
经验教训:在将数据投入使用之前始终对其进行测试。
旁注:这是我在 Whosebug 上的第一个问题,如此快速、优质和有用的回复让我不知所措。
您收到此错误是因为您的列表没有元素,row.find_all("td")
找不到任何内容,您必须检查 html 结构或使用 select
方法.
select()
return 通过 CSSS 选择器选择的所有元素,它非常强大,您的代码将是这样的:
row_datas = soup.select("td") #Note that select() is method of a BeautifulSoup Object .
print row_datas
print row_datas[0]
您的输出显示至少有一行是 空:
[]Traceback (most recent call last):
^^
[]
是一个空列表,输出是由您的 print row_datas
行产生的。通常我希望在它和 Traceback
之间有一个换行符;也许你没有正确复制你的输出,或者你有一个控制台使用大小缓冲区而不是行缓冲导致它混合 stdout 和 stderr。
那是因为第一行中有 th
header 个单元格:
>>> rows = soup.select('table.contentTable tr')
>>> rows[0].find('td') is None
True
>>> rows[0].find_all('th')
[<th width="20%">Name</th>, <th>Meaning</th>, <th>Popular <br/>\nalternate spellings</th>]
还有一个这样的行,因此您必须进行防御性编码:
>>> rows[26]
<tr><th width="20%">Name</th><th>Meaning</th><th>Popular <br/>\nalternate spellings</th></tr>
您可以只测试是否有任何带有 if
语句的元素:
if row_datas:
print row_datas[0]
提取所有名称、含义和替代拼写的代码非常简单:
for row in soup.select('table.contentTable tr'):
cells = row.find_all('td')
if not cells:
continue
name_link = cells[0].find('a')
name, link = name_link.get_text(strip=True), name_link.get('href')
meaning, alt = (cell.get_text(strip=True) for cell in cells[1:])
print '{}: {} ({})'.format(name, meaning, alt)