【问题标题】:python beautifulsoup can't prettifypython beautifulsoup 不能美化
【发布时间】:2017-03-31 07:14:18
【问题描述】:

我好像做错了什么。我有一个使用 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。

【问题讨论】:

  • 拨打findAll()soup的类型是什么?运行type(soup)
  • "输出很乱,包括换行符 "\n"" - 哪个输出?你从哪里得到这个你不满意的输出?唯一可以在您给出的代码中输出任何内容的是print soup.prettify(),因为您说它会引发错误,所以这不可能。你最终想要做什么?如果在每个元素上使用.text 属性会怎样?
  • @CivFan 肯定是ResultSet
  • @AlexHall 只是试图引导 Eric 找到他自己的答案。 alecxe 在他的回答中指出了这一点。

标签: python beautifulsoup


【解决方案1】:

You can call prettify() on the top-level BeautifulSoup object, or on any of its Tag objects:

findAll 返回匹配标签列表,因此您的代码等于[tag1,tag2..].prettify() 而且它不起作用。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多