【问题标题】:Trying to get an element of a class using Selenium Python尝试使用 Selenium Python 获取类的元素
【发布时间】:2022-01-16 08:00:46
【问题描述】:

我刚开始学习python。所以在本章中,基本上是使用 selenium 创建一个价格跟踪器。

下面的照片是我尝试使用 selenium 获得的。

Screenshot

如果我尝试

search_box = driver.find_element(By.CLASS_NAME, "a-price a-text-price a-size-medium apexPriceToPay")

它显示了红色的线海,说no buch Message: no such element

那我试试

search_box = driver.find_element(By.CLASS_NAME, "a-offscreen")

输出为:

我真的是编程新手...所以我尝试在最后使用 .text,但没有运气!

我该怎么做才能得到价格?

【问题讨论】:

    标签: python html selenium web-scraping


    【解决方案1】:

    我会试试这个:

    search_box = driver.find_element(By.CLASS_NAME, "apexPriceToPay")
    

    或许

    search_box = driver.find_element(By.CSS_SELECTOR, ".a-price.a-text-price")
    

    为了给出准确的答案,我们需要查看整个页面的 HTML 以找到最短的唯一定位符

    【讨论】:

    • amazon.ca/Pure-Protein-Chocolate-100-Powder/dp/B00BMHB5WM/… 请原谅我发布了整个亚马逊链接。我真的不知道从哪里开始
    • 谢谢。我看到 apexPriceToPay 是一个唯一的类名。所以你可以使用search_box = driver.find_element(By.CLASS_NAME, "apexPriceToPay")。顺便说一句,不要忘记接受答案...
    【解决方案2】:

    你需要注意几件事:

    1. 您不能在 driver.find_element(By.CLASS_NAME, "classA classB classC classD") 中传递多个类名,因为它可能会引发 invalid selector

    2. 传递类名 a-offscreen 选择18 个元素,所以你甚至不能使用它。

    3. 你会看到输出如下:

      <selenium.webdriver.remote.webelement.WebElement (session="0e1349ab77fff9cc0f9c565cc173927d", element="bbd837af-3cdf-4bd1-825c-9fd8cd27f719")>
      

      当你打印元素本身时,你也不需要。


    解决方案

    要打印文本$20.97,您可以使用以下Locator Strategy

    • 使用xpathtext属性:

      print(driver.find_element(By.XPATH, "//td[starts-with(., 'Price')]//following-sibling::td[1]/span[contains(@class, 'a-price')]/span[@aria-hidden='true']").text)
      

    理想情况下,您需要为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下Locator Strategy

    • 使用xpath,第二个&lt;span&gt;get_attribute("innerHTML")

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[starts-with(., 'Price')]//following-sibling::td[1]/span[contains(@class, 'a-price')]/span[@aria-hidden='true']"))).get_attribute("innerHTML"))
      
    • 控制台输出:

      $20.97
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    您可以在How to retrieve the text of a WebElement using Selenium - Python找到相关讨论


    参考文献

    链接到有用的文档:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 2022-11-14
      • 1970-01-01
      • 2023-01-28
      • 2019-08-15
      • 2014-06-05
      • 2022-01-03
      相关资源
      最近更新 更多