在具有BeautifulSoup的类中查找Htags

2024-10-02 04:29:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在计算一篇文章中的所有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

The page html/css


Tags: to代码标记divarticle文章pagefind
2条回答

要仅统计/打印文章中的标题,请首先从soup中选择所有<article>,然后在选择中选择第二个find_all()标题:

import requests
from bs4 import BeautifulSoup

result = requests.get('https://www.prisjakt.nu/sa-valjer-du-ratt-grill ecXqqVohAAACIARDWF')

soup = BeautifulSoup(result.content, 'lxml')

for article in soup.select('article'):
    for heading in article.find_all(['h1', 'h2', 'h3','h4']):
        print(heading.name + ' ' + heading.text.strip())

输出:

h1 Så väljer du rätt grill
h4 Kolgrill, gasolgrill, elgrill – vad ska man egentligen välja? Här får du tipsen och råden du behöver innan du väljer!
h3 Kolgrillen
h4 Fördelar
h4 Nackdelar
h4 3 populäraste kolgrillarna våren 2021
h3 Grillkol eller briketter?
h3 Gasolgrillen
h4 3 populäraste gasolgrillarna våren 2021
h3 Elgrillen
h4 3 populäraste elgrillarna våren 2021
h3 Prisjakts grilltips

除了text.strip(),您还可以使用get_text(strip=True) `

您可以将soup.find_all调用应用于锚定在article选择上的soup对象。此外,由于h标记的范围从1到6,因此可以将re.compile对象传递给find_all

from bs4 import BeautifulSoup as soup
import re
results = soup.select_one('article').find_all(re.compile('h\d+'))

相关问题 更多 >

    热门问题