【发布时间】:2019-04-20 07:05:51
【问题描述】:
我有超过 1000 个具有不同格式、元素和内容的 html 文件。我需要递归地遍历每个元素并选择除<h1>element 之外的所有元素。
这是一个示例文件(请注意,这是文件中最小和最简单的文件,其余文件更大且更复杂,其中包含许多不符合任何单个模板的不同元素,除了以 @987654322 开头@元素):
<h1>CXR Introduction</h1>
<h2>Basic Principles</h2>
<ul>
<li>Note differences in density.</li>
<li>Identify the site of the pathology by noting silhouettes.</li>
<li>If you can’t see lung vessels, then the pathology must be within the lung.</li>
<li>Loss of the ability to see lung vessels is supplanted by the ability to see air-bronchograms.</li>
</ul>
<p><a href="./A-CXR-TERMINOLOGY-2301158c-efe4-456e-9e0b-5747c5f3e1ce.md">A. CXR-TERMINOLOGY</a></p>
<p><a href="./B-SOME-RADIOLOGICAL-PATHOLOGY-2610a46c-44ca-4f81-a496-9ea3b911cb4e.md">B. SOME RADIOLOGICAL PATHOLOGY</a></p>
<p><a href="./C-Approach-to-common-clinical-scenarios-0e8f5c90-b14b-48d4-8484-0b0f8ca4464c.md">C. Approach to common clinical scenarios</a></p>
我使用 beautifulsoup 编写了这段代码:
with open("file.htm") as ip:
#HTML parsing done using the "html.parser".
soup = BeautifulSoup(ip, "html.parser")
selection = soup.select("h1 > ")
print(selection)
我希望这会选择<h1> 元素下方的所有内容,但事实并非如此。使用soup.select("h1") 只选择一行,而不选择它下面的所有内容。我该怎么办?
【问题讨论】:
标签: python beautifulsoup