我想用文本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">… </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")>
编辑:
我设法通过单击显示更多按钮解决了这个问题。由于某些原因,即使页面中存在,我也无法提取内容。
根据您的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
您可以将以下CSS选择器用于span
,并带有“提取此文本”:
.mainText>.moreContent>span:first-child
或
.mainText>.moreContent>span:nth-child(1)
希望对您有帮助!
要从第一个<span>
中提取文本,即提取此文本,您需要为visibility_of_element_located()
引入WebDriverWait,并且可以使用以下任何一个Locator Strategies:
使用CSS_SELECTOR
和text
属性:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "p.mainText span.moreContent>span"))).text)
使用XPATH
和get_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