用硒提取第一个大龄儿童

问题描述 投票:1回答:3

我想用文本span提取第一个Extract this text。已经尝试过:

element.find_element_by_css_selector(".moreContent span:nth-child(1)").text.strip('"')

这不起作用,我不确定为什么。输出为空。

<p class="mainText">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry.
  <span class="moreEllipses">…&nbsp;</span>
  <span class="moreContent">
    <span> Extract this text </span>
    <span class="link moreLink">Show More</span>
  </span>
</p>

但是我得到了这个,所以Selenium找到了元素,但是为什么输出为空:

<selenium.webdriver.remote.webelement.WebElement (session="e7012b303842651848aa0b0e40f5d5c1", element="df5644e9-fc98-4300-ad86-9ff433154d82")>

编辑:

我设法通过单击显示更多按钮解决了这个问题。由于某些原因,即使页面中存在,我也无法提取内容。

python selenium xpath css-selectors webdriverwait
3个回答
0
投票

根据您的cssSelector,看来您的目标是以下位置

<span> Extract this text </span>

您可以在Xpath下使用:

(//p[@class='mainText']//span[@class='moreContent']/span)[1]

OR

(//span[@class='moreContent']/span)[1]

示例代码:

element = driver.find_element_by_xpath("(//p[@class='mainText']//span[@class='moreContent']/span)[1]").text

0
投票

您可以将以下CSS选择器用于span,并带有“提取此文本”:

.mainText>.moreContent>span:first-child

.mainText>.moreContent>span:nth-child(1)

希望对您有帮助!


0
投票

要从第一个<span>中提取文本,即提取此文本,您需要为visibility_of_element_located()引入WebDriverWait,并且可以使用以下任何一个Locator Strategies

  • 使用CSS_SELECTORtext属性:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "p.mainText span.moreContent>span"))).text)
    
  • 使用XPATHget_attribute()方法:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//p[@class='mainText']//span[@class='moreContent']/span"))).get_attribute("innerHTML"))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
© www.soinside.com 2019 - 2024. All rights reserved.