如何以纯文本形式提取维基百科页面的所有部分?



我有以下python代码,它只提取了"人工智能"这篇文章的介绍,而我想提取所有的子部分(历史,目标…)

import requests
def get_wikipedia_page(page_title):
endpoint = "https://en.wikipedia.org/w/api.php"
params = {
"format": "json",
"action": "query",
"prop": "extracts",
"exintro": "",
"explaintext": "",
"titles": page_title
}
response = requests.get(endpoint, params=params)
data = response.json()
pages = data["query"]["pages"]
page_id = list(pages.keys())[0]
return pages[page_id]["extract"]
page_title = "Artificial intelligence"
wikipedia_page = get_wikipedia_page(page_title)

有人建议使用另一种方法解析html并使用BeautifulSoup将其转换为文本:

from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://en.wikipedia.org/wiki/Artificial_intelligence"
html = urlopen(url).read()
soup = BeautifulSoup(html, features="html.parser")
# kill all script and style elements
for script in soup(["script", "style"]):
script.extract()    # rip it out
# get text
text = soup.get_text()
# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in 
line.split("  
"))
# drop blank lines
text = 'n'.join(chunk for chunk in chunks if chunk)
print(text)

这不是一个足够好的解决方案,因为它包括网站上出现的所有文本(如图像文本),并且它包括文本中的引用(例如[1]),而第一个脚本删除了它们。

我怀疑维基百科的api应该提供一个更优雅的解决方案,如果一个人只能得到第一部分,那将是相当奇怪的?

检索维基百科页面

就像在我们的web浏览器中一样,我们可以通过URL检索完整的维基百科页面,并使用Beautiful Soup解析HTML响应。

Wikepedia的API

作为替代,我们可以使用API,参见Wikipedia的API文档。

提取纯文本

当使用action=queryformat=json时,您可以使用以下4个选项进行文本提取:

  • titles=Artificial intelligence
  • 页面
  • prop=extracts使用TextExtracts扩展名
  • exintro限制对第一个节标题()之前的内容的响应,删除它以获得包含节的整个文本)
  • explaintext提取为纯文本响应而不是HTML

的例子:https://en.wikipedia.org/w/api.php?action=query&格式= json&标题=人工% 20 intelligence&支持= extracts& explaintext

分别获取各部分

使用action=parseformat=json以及这些选项来检索区段:

  • page=Artificial intelligence获取本页内容
  • prop=sections只返回section

还有一个API沙盒您可以尝试几个参数。生成的GET请求将检索示例页面的所有部分"人工智能":https://en.wikipedia.org/wiki/Special: ApiSandbox #行动= parse&格式= json&页面=人工% 20 intelligence&支持= sections& formatversion = 2

这将以包含所有节的JSON响应:

{
"parse": {
"title": "Artificial intelligence",
"pageid": 1164,
"sections": [
{
"toclevel": 1,
"level": "2",
"line": "History",
"number": "1",
"index": "1",
"fromtitle": "Artificial_intelligence",
"byteoffset": 5987,
"anchor": "History",
"linkAnchor": "History"
}
}

(简化,只保留第一部分)

要获取其中一个部分的文本,指定该部分作为查询参数(通过id或标题),例如section=1&sectiontitle=History:https://en.wikipedia.org/wiki/Special: ApiSandbox #行动= parse&格式= json&页面= Artificial_intelligence&部分= 1,sectiontitle = History& formatversion = 2

检索文本(HTML格式):

{
"parse": {
"title": "Artificial intelligence",
"pageid": 1164,
"revid": 1126677096,
"text": "<div class="mw-parser-output"><h2><span class="mw-headline" id="History">History</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Artificial_intelligence&amp;action=edit&amp;section=1" title="Edit section: History">edit</a><span class="mw-editsection-bracket">]</span></span></h2>n<style data-mw-deduplicate="TemplateStyles:r1033289096">.mw-parser-output .hatnote{font-style:italic}.mw-parser-output div.hatnote{padding-left:1.6em;margin-bottom:0.5em}.mw-parser-output .hatnote i{font-style:normal}.mw-parser-output .hatnote+link+.hatnote{margin-top:-0.5em}</style><div role="note" class="hatnote navigation-not-searchable">Main articles: <a href="/wiki/History_of_artificial_intelligence" title="History of artificial intelligence">History of artificial intelligence</a> and <a href="/wiki/Timeline_of_artificial_intelligence" title="Timeline of artificial intelligence">Timeline of artificial intelligence</a>

注意:以上回复被截断,只显示文本的一个样本。

虽然上面的文本内容被格式化为HTML,但可能有选项将其转换为纯文本。

参见

  • 通过API从mediawiki页面获取文本内容
  • 如何从维基百科中获取纯文本

Python代码

你也可以使用Python,比如

  1. packagewikipedia:
import wikpedia
wikipedia.set_lang('en')
page = wikipedia.page('Artificial intelligence')
print(page.content)
  1. 一个Gist fromSai Kumar Yava (scionoftech)使用requests:在plan text
  2. 中获取维基百科页面内容的小Python代码

最新更新