python - 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。)
解决方案
使用.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}}
推荐阅读
- reporting-services - SSRS - 之前每一行的小计,与组无关
- azure-data-factory - 将源文件中的列与接收器表列匹配,以确保它们使用 Azure 数据工厂匹配
- java - JFoenix - 删除 JFXDialog 中的多余空间
- python - 当我在pygame中不按住空格键时,如何制作连续移动的子弹?
- ubuntu - 加载共享库时出错:libX11.so.6
- javascript - 【Rails6】Action Cable don't GET '/action'
- c - 如何使用 Printf 根据列对齐我的最后一列
- c++ - 在 C++ 中从 .csv 读取文件
- kotlin - 在 ktor 服务器中全局处理 http 异常是个好主意吗?
- javascript - Linebreak 不会被解释为 Node JS 中的换行符