我在计算一篇文章中的所有H标记时遇到了一点问题,我需要将搜索保持在代码的主要文章类部分中。看起来像这样
<article class="Article-p6ncbx-0 hxYamq">
<div class ="">
<div class ="">
<div class ="">
<div class ="">
<div class ="">
<div class ="">
<h3>I need to search this one</h3>
</div>
</div>
</div>
</div>
</div>
</div>
</article>
<footer class="Footer-238971asd sdjkYsd">
<div class ="">
<div class ="">
<div class ="">
<div class ="">
<h3>But I dont want to find this H3-tag</h3>
运行此代码将在页面上显示所有H1到H4标记,还包括页眉和页脚,这两个标记都在文章类之外
for heading in soup.find_all(["h1", "h2", "h3","h4"]):
print(heading.name + ' ' + heading.text.strip())
我是新手,很难理解如何将搜索保持在article类中。任何帮助都将不胜感激
我知道这个话题以前已经被详细讨论过了,但是我找不到一个解决这个问题的方法,我需要把它留在课堂里。如果这个问题可以通过简单的搜索解决,请随时纠正我
下面是整个事情的截图Here is the actual page also
要仅统计/打印文章中的标题,请首先从soup中选择所有
<article>
,然后在选择中选择第二个find_all()
标题:输出:
除了
text.strip()
,您还可以使用get_text(strip=True)
`您可以将
soup.find_all
调用应用于锚定在article
选择上的soup
对象。此外,由于h
标记的范围从1到6,因此可以将re.compile
对象传递给find_all
:相关问题 更多 >
编程相关推荐