如何使用特定的h1标记文本名访问div类?

2024-10-05 12:18:50 发布

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

我需要获取特定H1类文本的div类内部的信息。下面是HTML代码:

html <head> </head> <body> <h1 class="SAyv5">WHO Coronavirus disease (COVID-19) situation reports</h1> <div> This content1 I need </div> <div> This content2 I need </div> <div> This content3 I need </div> <p>This is my first page.</p> <h1>A secondary header.</h2> <div> This content4 I need </div> <p>Some more text.</p> </body>

这里我只需要div类的内容,它位于H1选项卡文本“世卫组织冠状病毒病(新冠病毒-19)情况报告”下。同样,有多个H1标签,但我需要访问他们只有一个H1标签文本我必须通过“世卫组织冠状病毒病(新冠病毒-19)情况报告”这一文本访问它们。


Tags: 文本div信息报告情况body标签need
2条回答

如果我理解正确,您可能正在寻找以下内容:

ht = """your html above, fixed"""
from bs4 import BeautifulSoup as bs
soup = bs(ht,'lxml')

targets = soup.find_all('h1',string="WHO Coronavirus disease (COVID-19) situation reports")
for target in targets:
    for t in target.fetchNextSiblings('div'):
        print(t.text)

这将从<div>元素后面的所有<h1>元素中输出具有所需文本的文本

如果你需要在css中访问它们,我会这样做

html

    <head>
    </head>
    <body>
       <div id="content1Container">
        <h1 class="SAyv5">WHO Coronavirus disease (COVID-19) situation reports</h1>
        <div> This content1 I need </div>
        <div>  This content2 I need </div>
        <div>  This content3 I need </div>
       </div>
       
       <div id="otherContentContainer">
         <p>This is my first page.</p>
         <h1>A secondary header.</h2>
         <div>This content4 I need</div>
         <p>Some more text.</p>
       </div>
       
    </body>

CSS

#content1Container div{
  background-color: red;
}

相关问题 更多 >

    热门问题