首页 > 解决方案 > BeautifulSoup 无法访问标签

问题描述

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

textdump 文档包含多篇文章,每篇文章都包含在一个<page>标签中。

不幸的是,关于文档结构的某些内容似乎与 BeautifulSoup 不兼容:在 each<page>中,文章的正文包含在一个<text>块中:

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

一旦我选择了某个<page>块,我应该能够以page.text.string.

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

不幸的是,它似乎page.text仍然被解释为与page.string向后兼容性相同。(编辑:getattr(page, "text")做同样的事情。)

有什么办法可以解决这个问题并访问一个名为的 HTML 标记<text>

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

标签: pythonparsingbeautifulsouptagshtml-parsing

解决方案


使用.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}}

推荐阅读