在BeautifulSoup中,循环内部不能打印输出。这是因为BeautifulSoup解析HTML时,会检查标签是否正确闭合,因此需要先将整个HTML页面解析完毕,然后再遍历解析的结果。如果在循环内部打印输出,可能会因为标签未闭合而导致解析出错,因此需要将打印输出移到循环外部。
以下是一个示例代码:
from bs4 import BeautifulSoup
html = 'Hello World!
Beautiful Soup'
soup = BeautifulSoup(html, 'html.parser')
# 正确的写法
for tag in soup.find_all('div'):
span = tag.find('span')
print(span.text)
# 错误的写法
for tag in soup.find_all('div'):
span = tag.find('span')
# 在循环内部打印输出
print(span.text)
在以上示例中,第一种方式是正确的写法,将打印输出移到了循环外部;而第二种方式是错误的写法,将打印输出移到了循环内部。