如何提取隐藏可见性模式下的文本?

2024-03-28 23:11:57 发布

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

我想提取一本书中的星星数亚马逊网站. 我尝试用Xpath来做,但它显示了错误:-

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[4]/div/div1/div/div/div/div/div1"}

如图所示,我想提取部分:-“4.7/5星”,但由于是能见度模式,我无法提取信息。在

有人能帮我吗??
提前谢谢

enter image description here


Tags: tonodivmessage网站selenium错误element
1条回答
网友
1楼 · 发布于 2024-03-28 23:11:57

当鼠标悬停在元素上时,将显示该元素。可能是使用AJAX查询。您需要执行鼠标悬停,然后,当它显示时,捕捉文本。在

  1. 为此,您需要导入ActionChains

from selenium.webdriver.common.action_chains import ActionChains

  1. 然后执行鼠标悬停:

element_to_hover = driver.find_element_by_xpath(...) hover_action = ActionChains(driver).move_to_element(element_to_hover) hover_action.perform()

  1. 一旦元素显示出来,您只需通过xpath找到文本元素。在

(也许您需要在第2步和第3步之间time.sleep(1)。)

编辑

已经过测试,并且可以工作:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time

chrome_path = r"chromedriver.exe"

driver = webdriver.Chrome(chrome_path)

driver.get("https://www.amazon.com/s/ref=sr_pg_2?rh=n%3A133140011&page=1&sort=salesrank&unfiltered=1&ie=UTF8")

element_to_hover = driver.find_element_by_xpath("""//*[@id="result_0"]/div/div/div/div[2]/div[3]/div[2]/div/span/span/a/i[1]/span""")
hover_action = ActionChains(driver).move_to_element(element_to_hover)
hover_action.perform()
time.sleep(2)
stars_count = driver.find_element_by_xpath("""//*[@id="a-popover-content-3"]/div/div/div/div[1]/span""")
print stars_count.get_attribute('innerHTML')

相关问题 更多 >