【问题标题】:BeautifulSoup can't access content of <text> tagBeautifulSoup 无法访问 <text> 标签的内容
【发布时间】:2019-02-03 22:52:27
【问题描述】:

我正在使用 BeautifulSoup(4.4 版)预处理来自 https://dumps.wikimedia.org/enwiki/ 的 Wikipedia textdump 以进行进一步解析。

textdump 文档包含多篇文章,每篇文章都包含在&lt;page&gt; 标记中。

不幸的是,文档结构的某些内容似乎与 BeautifulSoup 不兼容:在每个 &lt;page&gt; 中,文章的正文包含在 &lt;text&gt; 块中:

<text xml:space="preserve">...</text>

一旦我选择了某个&lt;page&gt; 块,我应该能够以page.text.string 访问文本块的内容。

在 BeautifulSoup 中,.text 过去是为括号中的标签内容保留的。在更新的版本中,.string 用于此目的。

不幸的是,为了向后兼容,page.text 的解释似乎仍与 page.string 相同。 (编辑:getattr(page, "text") 也一样。)

有什么办法可以解决这个问题并访问一个名为 &lt;text&gt; 的 HTML 标记?

(编辑:有关语法示例,请参阅https://pastebin.com/WQvJn0gf。)

【问题讨论】:

  • 请提供您要解析的页面的确切 URL。您提供的链接不包含 &lt;text&gt; 标记。
  • @DeepSpace 下面是一个语法示例:pastebin.com/WQvJn0gf(我实际上是在解析 dumps.wikimedia.org/enwiki/latest/…,它是 595(未压缩)MB 的文本,所以这是不合适的。)
  • 使用getattr(page, 'text') 能解决问题吗?
  • @Chillie 这与直接访问 .text 具有相同的结果 - 它返回具有 &lt;page&gt; 内容的 .string 等效块。
  • 你使用的是哪个解析器?

标签: python parsing beautifulsoup tags html-parsing


【解决方案1】:

使用.find.text 按预期工作:

from bs4 import BeautifulSoup

string = '''<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.10/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.10/ http://www.mediawiki.org/xml/export-0.10.xsd" version="0.10" xml:lang="en">
  <siteinfo>...</siteinfo>
  <page>
    <title>AccessibleComputing</title>
    <ns>0</ns>
    <id>10</id>
    <redirect title="Computer accessibility" />
    <revision>
      <id>854851586</id>
      <parentid>834079434</parentid>
      <timestamp>2018-08-14T06:47:24Z</timestamp>
      <contributor>
        <username>Godsy</username>
        <id>23257138</id>
      </contributor>
      <comment>remove from category for seeking instructions on rcats</comment>
      <model>wikitext</model>
      <format>text/x-wiki</format>
      <text xml:space="preserve">#REDIRECT [[Computer accessibility]]

{{R from move}}
{{R from CamelCase}}
{{R unprintworthy}}</text>
      <sha1>42l0cvblwtb4nnupxm6wo000d27t6kf</sha1>
    </revision>
  </page>
...
</mediawiki>'''

soup = BeautifulSoup(string, 'html.parser')   
page_tag = soup.find('page')
text_tag = page_tag.find('text')
print(text_tag.text)
# #REDIRECT [[Computer accessibility]]

# {{R from move}}
# {{R from CamelCase}}
# {{R unprintworthy}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-14
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多