【发布时间】:2017-06-19 18:26:51
【问题描述】:
我无法让下面的 county 列表填充我循环的结果。当我打印出每次迭代的结果以及列表中项目的索引时,我看到每次都得到一个 0 的索引,这表明数据在每次循环后没有保留在列表中。因此,当我在循环完成后尝试对 county 循环进行索引时,当然其中根本没有数据,所以我得到了“列表索引超出范围错误”。
我研究了我不断收到的“列表索引超出范围”错误,我知道我收到它是因为 county 列表是空的,但为什么它是空的?
构成target_divs 列表中一项的 HTML 源代码如下所示:
<div class="school-type-list-text">
<div class="table_cell_county"><a href='/alabama/autauga-county'>Autauga County</a></div>
<div class="change_div"></div>
<div class="table_cell_other">7<span> Schools</span></div>
<div class="table_cell_other">1,587<span> Students</span></div>
<div class="table_cell_other">8%<span> Minority</span></div>
<div class="break"></div>
这是我的脚本:
import urllib2
from bs4 import BeautifulSoup
import pandas
import csv
page1 = 'https://www.privateschoolreview.com/alabama'
alabama = urllib2.urlopen(page1)
soup = BeautifulSoup(alabama, "lxml")
target_divs = soup.find_all("div", class_= "school-type-list-text")
for i in target_divs:
county = i.find_all("div", class_= "table_cell_county")
for i in county:
print i.text
print county.index(i)
print county
print county[0]
@Software2 建议更改循环光标后更新,但我仍然收到相同的错误:
import urllib2
from bs4 import BeautifulSoup
import pandas
import csv
page1 = 'https://www.privateschoolreview.com/alabama'
alabama = urllib2.urlopen(page1)
soup = BeautifulSoup(alabama, "lxml")
target_divs = soup.find_all("div", class_= "school-type-list-text")
for div in target_divs:
counties = div.find_all("div", class_= "table_cell_county")
for county in counties:
print county.text
print counties.index(county)
print counties
【问题讨论】:
-
您有两个引用
i的for循环 -
OP 已经粘贴了代码的输出。请不要编辑。