python - Python Beautiful Soup 循环
问题描述
我试图让一个循环多次通过链接,它只运行一次,似乎忽略了除了 Beautiful Soup 代码之外的所有其他代码
import requests
import bs4
x = 0
while x < 3:
print(x)
res = requests.get('https://en.wikipedia.org/wiki/Special:Random')
soup = bs4.BeautifulSoup(res.text, 'lxml')
i = soup.select('.firstHeading')
print(i.text)
x += 1
else:
print('Done')
f = open('text.txt', 'w')
f.write('soup')
f.close()
解决方案
你有错print(i.text)
,
i
在List
你的情况下,
可能需要print(i[0].text)
:
import requests
import bs4
x = 0
while x < 3:
print(x)
res = requests.get('https://en.wikipedia.org/wiki/Special:Random')
soup = bs4.BeautifulSoup(res.text, 'lxml')
i = soup.select('.firstHeading')
print(i[0].text)
x += 1
else:
print('Done')
f = open('text.txt', 'w')
f.write('soup')
f.close()
你将有输出:
0
Liu Jianfu
1
Rees Edgar Tulloss
2
List of Ed episodes
Done
推荐阅读
- javascript - Google Maps API - 根据英里计算缩放
- laravel - 如何在模型本身的 Laravel 中将 unix 时间戳转换为 Carbon 实例?
- scala - 如何使用 Scala 在 Spark 数据框中为每个不同的列值创建行 ID 列
- ios - 使用什么 CIFilter 来获得扫描效果?
- wpf - 使用网格控件调整大小时应用程序内存迅速增加
- c# - Unity 的 GetComponent 通过字符串(或通过从另一个脚本传递的其他方法)
- c# - 如何为 WPF 应用程序和 ASP.net 应用程序创建安装程序?
- c++ - 从另一个程序检查 cin 而无需在 OSX 中等待
- javascript - 如何安全地跨域将表单从静态 html 站点提交到服务器端后端?
- file - 将具有特定文件名的文件从一个文件夹移动到另一个文件夹