我無法從下面的county
列表中填充循環結果。當我將每次迭代的結果與列表中項目的索引一起打印出來時,我發現每次都得到一個0的索引,表明每次循環後數據都不會保留在列表中。因此,當我在循環完成後嘗試索引county
循環時,當然沒有數據,所以我得到'列表索引超出範圍錯誤'。具有循環的Python列表人口
我研究了「列表索引超出範圍」錯誤,我不斷收到,我明白我得到它,因爲county
列表爲空,但爲什麼它是空的?
的HTML源代碼,構成了在target_divs
列表中的一個條目看起來是這樣的:
<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]
更新後@軟件2勸改變環路光標,但我仍然得到相同的錯誤:
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
你有兩個'for'循環,即參考'i' – depperm
的OP已經粘貼從代碼的輸出。請不要編輯它。 –