【问题标题】:How to extract text before "br"?如何提取“br”之前的文本?
【发布时间】:2015-12-08 15:20:36
【问题描述】:

我有一个小问题。我正在使用 python 2.7.8。我正在尝试提取应该在 br> 之前的文本。我喜欢:

<html>
<body>
<div class="entry-content" >
<p>Here is a listing of C interview questions on “Variable Names” along with answers, explanations and/or solutions:
</p>

<p>1. C99 standard guarantees uniqueness of ____ characters for internal names.<br>
a) 31<br>
b) 63<br>
c) 12<br>
d) 14</p>
<p> more </p>
<p>2. C99 standard guarantess uniqueness of _____ characters for external names.<br>
a) 31<br>
b) 6<br>
c) 12<br>
d) 14</p>
 </div>
</body>
</html>

我尝试过的代码目前在 br> 之后而不是在 br 之前。这是代码:

from BeautifulSoup import BeautifulSoup, NavigableString, Tag
soup2 = BeautifulSoup(htmls)

for br2 in soup2.findAll('br'):
    next = br2.previousSibling
    if not (next and isinstance(next,NavigableString)):
        continue
    next2 = next.previousSibling
    if next2 and isinstance(next2,Tag) and next2.name == 'br':
        text = str(next).strip()
        if text:

            print "Found:", next.encode('utf-8')

输出给了我:

Found: 
a) 31
Found: 
b) 63
Found: 
c) 12
Found:
d) 14 
a) 31
Found: 
b) 6
Found: 
c) 12
Found:
d) 14 
Found:

知道我哪里做错了。

【问题讨论】:

  • 任何一个???我还在尝试但失败了......
  • 井列表不在里面。如果你能表达你的意思?

标签: python html beautifulsoup html-parsing


【解决方案1】:

首先,我会改用BeautifulSoup version 4。 BeautifulSoup3 已经很老了,不再维护了:

美汤 3 已被美汤 4 取代。

Beautiful Soup 3 仅适用于 Python 2.x,但 Beautiful Soup 4 也适用 适用于 Python 3.x。 Beautiful Soup 4 速度更快,功能更多, 并与 lxml 和 html5lib 等第三方解析器一起使用。一旦 测试期结束,您应该使用 Beautiful Soup 4 进行所有新的 项目。

运行:

pip install beautifulsoup4

并从以下位置更改您的导入语句:

from BeautifulSoup import BeautifulSoup

到:

from bs4 import BeautifulSoup

现在,我要做的是找到问题文本和get the following br siblings。对于每个兄弟姐妹,获取next_sibling 这将是答案选项。工作代码:

soup = BeautifulSoup(data, "html5lib")  # using "html5lib" parser here

for question in soup.find_all(text=re.compile(r"^\d+\.")):
    answers = [br.next_sibling.strip() for br in question.find_next_siblings("br")]

    print(question)
    print(answers)
    print("------")

对于问题中提供的示例 HTML,它会打印:

1. C99 standard guarantees uniqueness of ____ characters for internal names.
[u'a) 31', u'b) 63', u'c) 12', u'd) 14']
------
2. C99 standard guarantess uniqueness of _____ characters for external names.
[u'a) 31', u'b) 6', u'c) 12', u'd) 14']
------

请注意,您可能需要安装html5lib library

pip install html5lib

【讨论】:

  • 我在 python 2.7.8 上。 html5lib 和 b4 支持吗?
  • 我收到此错误:eatureNotFound:找不到具有您要求的功能的树生成器:html5lib。需要安装解析器库吗?
  • 我已经安装了b4和html5
  • @user3440716 好吧,这说明你还没有安装html5lib:运行pip install html5lib
  • 我安装了但我做了更改 "soup = BeautifulSoup(htmls, "lxml") " 所以它也是替代答案:) 并且正在工作
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多