python - 如何提取处于隐藏可见性模式的文本?

标签 python selenium

我想提取一本书从 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 星”,但由于它是可见性模式,我无法提取信息。

谁能帮帮我吗?
提前致谢

enter image description here

最佳答案

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

  1. 为此,您需要导入 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/

    相关文章:

    javascript - 如何使用 HTML/Javascript 传递 URL 参数

    python - 遍历字典列表并创建新的字典列表

    python - 使用 boto3 从 S3 存储桶下载文件时出现 ValueError?

    python - 在 Python 中 reshape 附加列表 - 将列表拆分为列

    selenium - 在 colab 中安装并运行 selenium 浏览器

    python - 如何使用初始值递归地将参数输入到此函数中?

    java - 无法在 Eclipse 中找到或加载主类 org.testng.remote.RemoteTestNG

    java - "ExpectedConditions.visibilityOfElementLocated"和 "element.isDisplayed()"之间的确切区别是什么

    python - 无法从网页收集所有店铺名称

    xml - 测试 XML 响应的最佳方法是什么?