首页 > 解决方案 > 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()

标签: pythonloopsbeautifulsoup

解决方案


你有错print(i.text)

iList你的情况下,

可能需要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

推荐阅读