我想提取一本书从 amazon.com 获得的星星数。我尝试通过 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 星”,但由于它是可见性模式,我无法提取信息。
谁能帮帮我吗?
提前致谢
最佳答案
当鼠标悬停在元素上时,将显示该元素。可能是通过 AJAX 查询。您需要执行鼠标悬停,然后在其显示时捕获文本。
- 为此,您需要导入
ActionChains
从 selenium.webdriver.common.action_chains 导入 ActionChains
- 然后执行鼠标悬停:
element_to_hover = driver.find_element_by_xpath(...)
hide_action = ActionChains(driver).move_to_element(element_to_hover)
hide_action.perform()
- 显示元素后,您只需通过 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')
关于python - 如何提取处于隐藏可见性模式的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45393389/