【发布时间】:2016-11-02 16:48:20
【问题描述】:
在 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> 标签之间的所有内容。我的目标是获取这篇文章的所有标题和纯文本内容。我该怎么做呢?
在上面发布的示例中,我想要的输出是包含:
- 所有标题(Amadeus(电影)、情节、演员、接待处等)
- 本页内的所有文字(
<p>标签之间) - 忽略引用
【问题讨论】:
-
您能否详细说明“获取所有标题”是什么意思 - 您可以发布您想要的输出吗?谢谢。
-
@alecxe 我添加了我想要的输出。
标签: python python-2.7 beautifulsoup