gpt4 book ai didi

python beautifulsoup 无法美化

转载 作者:太空宇宙 更新时间:2023-11-04 00:43:57 24 4
gpt4 key购买 nike

我好像做错了什么。我有一个使用 urllib 提取的 HTML 源代码。基于此 HTML 文件,我使用 beautifulsoup 来查找具有基于指定数组的 ID 的所有元素。这对我有用,但是输出很乱并且包含换行符“\n”。

  • python : 2.7.12
  • BeautifulSoup: bs4

我曾尝试使用 prettify() 来更正输出但总是出现错误:

AttributeError: 'ResultSet' 对象没有 'prettify' 属性

import urllib
import re
from bs4 import BeautifulSoup

cfile = open("test.txt")
clist = cfile.read()
clist = clist.split('\n')

i=0

while i<len (clist):
url = "https://example.com/"+clist[i]
htmlfile = urllib.urlopen (url)
htmltext = htmlfile.read()

soup = BeautifulSoup (htmltext, "html.parser")
soup = soup.findAll (id=["id1", "id2", "id3"])

print soup.prettify()
i+=1

我确定我在这一行中忽略了一些简单的事情:

soup = soup.findAll (id=["id1", "id2", "id3"])

我只是不确定是什么。对不起,如果这是一个愚蠢的问题。我只使用 Python 和 Beautiful Soup 几天。

最佳答案

您正在将 soup 变量重新分配给 .findAll() 的结果,它是一个 ResultSet 对象(基本上是一个列表标签)没有 prettify() 方法。

解决方案是让 soup 变量指向 BeautifulSoup 实例。

关于python beautifulsoup 无法美化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40643147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com