Python中文
首页
教程
问答
标签
搜索
登录
注册
带循环的Python列表填充
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我在获取下面的<code>county</code>列表时遇到问题,无法用循环中的结果填充。当我打印出每次迭代的结果以及列表中项目的索引时,我看到我每次都得到一个0的索引,这表明数据在每次循环之后都不会持久化在列表中。因此,当我试图在循环完成后索引<code>county</code>循环时,其中当然根本没有数据,因此我得到了“list index out out range error”</p> <p>我研究了我一直得到的“list index out out range”错误,我明白我之所以得到它是因为<code>county</code>列表是空的,但是为什么它是空的呢?在</p> <p>组成<code>target_divs</code>列表中一个条目的HTML源代码如下所示:</p> <pre><code><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> </code></pre> <p>这是我的剧本:</p> ^{pr2}$ <p>@Software2建议更改循环光标后进行更新,但我仍然得到相同的错误:</p> <pre><code>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 </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>我可能错了你能试试这个吗。似乎您在嵌套循环中使用了相同的i</p> <pre><code>for i in target_divs: county = i.find_all("div", class_= "table_cell_county") for j in county: print j.text print county.index(j) </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
使用Python创建一个非常大的二进制频率矩阵来运行协作过滤
8 回答
使用Python创建一张HTML网页,其中在不同颜色中重复n遍显示“Hello World”的方法
6 回答
使用Python创建一组唯一的值length L
5 回答
使用python创建不同表格的透视表
5 回答
使用python创建不和谐频道
9 回答
使用python创建不存在的多个文件夹
10 回答
使用python创建串行远程文件
6 回答
使用python创建交互式仪表板时出现问题
2 回答
使用python创建交互式绘图
4 回答
使用python创建交互式自动电子邮件
3 回答
使用Python创建价格列表
3 回答
使用python创建修改的txt文件
2 回答
使用Python创建全局变量,初始化后更改值
8 回答
使用Python创建关键字搜索词数组
8 回答
使用Python创建具有不均匀块大小/堆叠条形图的热图
3 回答
使用Python创建具有依赖于另一列的值的列
10 回答
使用Python创建具有多列的HTML表
8 回答
使用Python创建具有时间范围数据的等距数据帧
6 回答
使用Python创建具有特定顺序或属性的XML文件
8 回答
使用Python创建具有级联功能的搜索栏
1 回答