gpt4 book ai didi

python - BeautifulSoup - 类型错误 : sequence item 0: expected str instance

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:43 27 4
gpt4 key购买 nike

我使用 python 制作了一个网络爬虫,一切运行正常,直到到达这部分代码:

    # Use BeautifulSoup modules to format web page as text that can
# be parsed and indexed
#
soup = bs4.BeautifulSoup(response, "html.parser")
tok = "".join(soup.findAll("p", text=re.compile(".")))
# pass the text extracted from the web page to the parsetoken routine for indexing
parsetoken(db, tok)
documents += 1

我得到的错误是TypeError:序列项0:预期的str实例,在代码中的tok行周围找到标签。
我认为我的语法可能是问题,但我不确定。我该如何解决这个问题?

最佳答案

这里有几个问题:

  • 首先,我不确定您从哪里得到的 response from,但这应该是一个实际的 HTML 字符串。确保您不仅仅是从抓取网站中捕获“响应”代码来告诉您是否成功。
  • 更重要的是,当您执行“findAll”时,请注意,这将返回 BeautifulSoup 对象的列表,而不是字符串列表。所以“join”命令不知道如何处理这些。它查看列表中的第一个对象,发现它不是一个字符串,这就是为什么它会出错并提示它“expected str instance ”。好消息是您可以使用 .text从给定的 <p> 中提取实际文本元素。
  • 即使您确实使用 .text从每个 <p> 中提取实际文本对象,你的join()如果您的列表是 unicode 的混合,可能仍然会失败和str格式。因此,在加入之前,您可能需要执行一些编码技巧才能使所有内容都具有相同类型。

这是我使用这个页面所做的一个示例:

>>> import bs4, re
>>> import urllib2
>>> url = "https://stackoverflow.com/questions/3925614/how-do-you-read-a-file-into-a-list-in-python"
>>> html = urllib2.urlopen(url).read()
>>> soup = bs4.BeautifulSoup(html, "html.parser")
>>> L = soup.findAll("p", text=re.compile("."))
>>> M = [t.text.encode('utf-8') for t in L]
>>> print(" ".join(M))

这将打印“P”标记中找到的所有内容的组合文本。

编辑:此示例基于 Python 2.7.x。对于 3.x,删除“.encode('utf-8')”。

关于python - BeautifulSoup - 类型错误 : sequence item 0: expected str instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54011146/

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