在Python中,我如何获取wikipedia文章中的所有标题和平面文本,比如:https://en.wikipedia.org/wiki/Amadeus_(film)。我现在的代码是:
from bs4 import BeautifulSoup
# ---- Definitions ----#
#Amount of documents
amount_of_documents = 1
#Directory of raw HTML documents
directory_of_raw_documents = "raw_documents/"
#Directory of parsed documents
directory_of_parsed_documents = "parsed_documents/"
# ---- Code ----#
def open_document():
for i in range (1, 1+1):
with open(directory_of_raw_documents + str(i), "r") as document:
html = document.read()
soup = BeautifulSoup(html, "html.parser")
body = soup.find('div', id='bodyContent')
for elements in body.find_all('p'):
print(elements.text)
open_document()
我正在加载一个下载的HTML文件,然后使用BeautifulSoup获取<p>
标记之间的所有内容。我的目标是获取本文的所有标题和纯文本内容。我该怎么做呢?在
在上面的示例中,我想要的输出将包含:
<p>
标记之间)
您可能会对使用专门的wikipedia页面解析器感兴趣,比如^{} package 。这样您就可以很容易地获得内容:
关于获取标题,下面是通过
^{pr2}$BeautifulSoup
获取它们的示例代码:h2 .mw-headline
是一个CSS selector,它将与h2
父元素下的mw-headline
类相匹配。在相关问题 更多 >
编程相关推荐