使用 Beautiful Soup 忽略维基百科中特定 ID 以下的内容
Ignoring content below certain ID in Wikipedia using Beautiful Soup
在以下链接中:
https://en.wikipedia.org/wiki/America
我需要抓取 h2、h3 和 p 标签内的内容。但是,我想忽略 header 和以下内容:
- "See Also"
- "Notes"
- "References"
- 全部忽略tables/urls
我如何在 Beautiful Soup 中完成此操作?我目前的代码如下:
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')
results = ""
for item in body.find_all(['h2','h3','p']):
results += item.get_text() + "\n"
results = results.replace("[edit]","")
print(results)
open_document()
我想要的输出在任何 table、查看全部、注释或参考部分中都没有任何内容。我宁愿不在 Python 2.7
中使用 Wikipedia 模块
soup.find(something)
表示你在整个文档中找到了一些东西,
如果你想忽略一些内容,你需要缩小范围,你可以使用:
soup.find(id = 'bodyContent') #this narrow the scope to the main content.
你可以使用 find_all:
soup.find(id = 'bodyContent').find_all(name=['h2','h3','p'], href=False)
在以下链接中:
https://en.wikipedia.org/wiki/America
我需要抓取 h2、h3 和 p 标签内的内容。但是,我想忽略 header 和以下内容:
- "See Also"
- "Notes"
- "References"
- 全部忽略tables/urls
我如何在 Beautiful Soup 中完成此操作?我目前的代码如下:
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')
results = ""
for item in body.find_all(['h2','h3','p']):
results += item.get_text() + "\n"
results = results.replace("[edit]","")
print(results)
open_document()
我想要的输出在任何 table、查看全部、注释或参考部分中都没有任何内容。我宁愿不在 Python 2.7
中使用 Wikipedia 模块soup.find(something)
表示你在整个文档中找到了一些东西, 如果你想忽略一些内容,你需要缩小范围,你可以使用:
soup.find(id = 'bodyContent') #this narrow the scope to the main content.
你可以使用 find_all:
soup.find(id = 'bodyContent').find_all(name=['h2','h3','p'], href=False)