python - Beautiful Soup 不能多次在 for 循环中工作
问题描述
我正在尝试运行 for 循环以从结果集中获取更多信息,但它在第一次运行后中断。
classid = ["ccid_10132191", "ccid_10132192", 'ccid_9829339', 'ccid_9829337']
with open('output.html') as fp:
soup = BeautifulSoup(fp, 'html.parser')
for classes in classid:
grade = str(soup.find_all(id = '' + classes))
soup = BeautifulSoup(grade, 'html.parser')
print(soup.find(class_='bold').contents)
当我运行它时,我会得到想要的结果,然后grade = str(soup.find_all(id = '' + classes))
停止工作并返回“[]”
str(soup.find_all(id = '' + classes) find blocks of HTML all similar to
<tr class="center" id="ccid_10132191">
<td>1(A)</td>
<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td>
<td align="left">CERAMICS BEGINNING <br><a href="teacherinfo.html?frn=0019424&nolink=true" title="Details about" class="button mini dialogM"><em class="ui-icon ui-icon-white ui-icon-contact"></em></a> <a href="mailto:">Email</a> - Rm: 156</td>
<td class="colorMyGrade"><a href="scores.html?frn=004615841&begdate=09/01/2024&enddate=11/14/2026&fg=Q1&schoolid=" class="bold">A<br>100</a></td>
<td class="colorMyGrade"><a href="scores.html?frn=0046041&fg=Q2&schoolid=">[ i ]</a></td>
<td class="colorMyGrade"><a href="scores.html?frn=004615041&begdate=09/01/2021&enddate=01/26/2022&fg=S1&schoolid=" class="bold">A<br>100</a></td>
<td class="notInSession"> <span class="screen_readers_only">Not available</span></td><td class="notInSession"> <span class="screen_readers_only">Not available</span></td><td class="notInSession"> <span class="screen_readers_only">Not available</span></td><td>0</td>
<td>0</td>
</tr>
唯一的区别是 id 和 text 内容
解决方案
正如@BoarGules 所说,发生这种情况是因为在 for 循环中重新定义了汤
解决方案是以下代码
classid = ["ccid_10132191", "ccid_10132192", 'ccid_9829339', 'ccid_9829337']
classhtml = []
with open('output.html') as fp:
soup = BeautifulSoup(fp, 'html.parser')
for classes in classid:
grade = str(soup.find_all(id = '' + classes))
classhtml.append(grade)
for classs in classhtml:
soup = BeautifulSoup(classs, 'html.parser')
print(soup.find(class_='bold').contents)
推荐阅读
- python - 表单字段的 Python Django PDF 展平
- javascript - 如何使用php中的while循环和javascript显示从数据库中获取的多个图像中的特定点击图像?
- mysql - 检查mysql是否有index null
- python - 字典列表中的唯一元素有效
- c# - 将架构添加到 Avro 片段 .Net
- asp.net - 有条件地使用 ADFS 登录
- three.js - 在 Three.js 中移动和更改外观(过山车视图)时使相机沿 z 轴旋转
- c++ - 对于 AIFF 格式的数据块中的字节,二进制补码如何工作?
- java - 从 Json 文件调用单个对象
- python - 在启动时,我出现黑屏,并带有文本“Ubuntu 18.04.2 LTS localhost tty1”