当通过 class 使用 selenium 和 python 查找元素时,如何仅从 <p> 和 <h2> 标签获取文本?

How can I get text from only <p> and <h2> tags when finding element by class with selenium and python?

我试图只从 h2 和第一个 p 标签中获取文本。我一直在使用 class 名称来查找 div 并且输出为我提供了 div 中的所有文本(很明显)。

这里是 HTML:

<div class="horoscope-content">
<h2> Today's Libra Horoscope for January 27, 2022 <span class="today-badge">TODAY</span></h2>
<p>Go with the flow, Libra. If you find that a situation isn't unfolding the way you'd like it to, take it as a sign to back off. Swimming upstream is hard work, so use your energy more efficiently by exploring different options. When you step back from a stressful situation, circumstances could turn around. Lighten up by considering other possibilities or talking it through with a helpful friend.</p>            
<p>What's in the stars for you tomorrow? <a href="/horoscopes/daily/libra/friday">Read it now</a>.</p>
<div class="dropdown-inline">Read the <b>daily horoscope</b> for another zodiac sign:<div id="dropdown_below_horoscope_dropdown" class="dropdown">

这是我使用的代码:

libra_content = driver.find_elements(By.CLASS_NAME, 'horoscope-content')

我假设答案是使用 xpath,但我不知道如何包含这两个标签。我需要使用两行单独的代码来完成它还是可以将两者合并为一个?

你可以使用:

libra_content = driver.find_elements(By.xpath, 'your_path')

读这个:

how to find elements by xpath

试试这个

<div>
    <h2 class="horoscope-content" >........</h2>
    <p class="horoscope-content" >........</p>            
    <p>.......</p>

libra_content = driver.find_elements(By.CLASS_NAME, 'horoscope-content')

您可以使用:

对于 h2:

libra_content = driver.find_element_by_css_selector("div[class='horoscope-content'] > h2 ")

对于 p:

libra_content = driver.find_element_by_css_selector("div[class='horoscope-content'] > p ")

libra_content = [[x.find_element(By.XPATH,'./h2[1]').text,x.find_element(By.XPATH,'./p[1]').text] for x in driver.find_elements(By.CLASS_NAME, 'horoscope-content')]

如果您想同时存储这两个值,您可以对这两个值执行类似的操作。

我使用 css 选择器解决了它,但没有将它们合二为一。另一位评论者使用 xpath 和 class 名称结合这两者的答案是一个可能的解决方案。

libra_h2 = driver.find_element(By.CSS_SELECTOR, 'div.horoscope-content > h2')
libra_p = driver.find_element(By.CSS_SELECTOR, 'div.horoscope-content > p')