【问题标题】:beautifulsoup .select returns nothingbeautifulsoup .select 不返回任何内容
【发布时间】:2018-01-25 20:31:36
【问题描述】:

我是一个业余的 Python 用户。目前我正在尝试找出漂亮的汤模块,但我无法通过 select 方法找到任何东西。 我已经制作了一个示例 html 文件(或多或少从“用 python 自动化无聊的东西”一书中复制),其内容是:

<html><head><title>The Website Title</title></head>
<body>
<p><strong>Hi There!</strong> here is a link to a website: <a href="http://
inventwithpython.com">a website thing</a>.</p>
<p class="slogan">this is a roundup, this is a low flying panic attack.</p>
<p>By <span id="author">Yonatan.</span></p>
</body></html>

我已经在 shell 中输入了这段代码:

examplefile = open('example.html')
examplesoup = bs4.BeautifulSoup(examplefile.read())
elem = examplesoup.select('#author')

但我得到的 elem 是一个空列表。我已经检查了 examplefile.read() 和它的真实情况。还尝试了 select('p') 并没有得到任何结果。 有什么很明显的东西我在这里想念的吗?我也是 html 新手。

【问题讨论】:

  • 这对我来说很好用。你的文件内容有问题。我希望你在做print(elem)。
  • 我是。我的文件内容有问题是什么意思? html还是脚本?顺便说一句,它在通过 .text 传递的请求对象上效果很好。
  • 'example.html' ...

标签: python html ubuntu beautifulsoup python-3.5


【解决方案1】:

试试这个

examplefile = open('example.html')
myfile=examplefile.read()
examplesoup = bs4.BeautifulSoup(myfile)
elem = examplesoup.select('#author')

这应该可以。

【讨论】:

  • 考虑为您的答案添加一些解释。为什么要试试这个? OP 的问题是什么?尝试此修复?
  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • @SebastianGodelet 这绝对不是仅链接的答案;一方面,答案中没有链接。但是,正如 pirho 所说,这个答案肯定需要改进/解释
  • @Sagar,对不起,我认为我在审核过程中选择了错误的东西
  • @SebastianGodelet 没关系!审查的道具,虽然! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 2018-02-15
  • 2022-11-28
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
相关资源
最近更新 更多