【问题标题】:Error using Selenium (Python): Unable to find class in HTML source code使用 Selenium (Python) 时出错:无法在 HTML 源代码中找到类
【发布时间】:2022-01-26 17:48:54
【问题描述】:

我正在学习如何使用 Selenium。我正在做一些测试,但得到了这个错误:

selenium.common.exceptions.NoSuchElementException:消息:无法定位元素:.layout layout-base

我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By

driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get("https://page.onstove.com/epicseven/global/list/e7en003?listType=2&direction=latest&page=1")
driver.find_element(By.CLASS_NAME,"layout layout-base")

我尝试使用find_element 查找的源代码。

我做错了什么?

【问题讨论】:

  • 也许可以尝试使用睡眠来让网站有时间将所有元素加载到 DOM 中

标签: python selenium xpath css-selectors classname


【解决方案1】:

您不能通过find_element(By.CLASS_NAME,"classname") 传递多个类名作为参数,这样做您将面临如下错误:

invalid selector: Compound class names not permitted

解决方案

您也可以使用以下任一Locator Strategies

  • 使用 CLASS_NAME layout

    driver.find_element(By.CLASS_NAME, "layout")
    
  • 使用 CLASS_NAME layout

    driver.find_element(By.CLASS_NAME, "layout-base")
    
  • 使用CSS_SELECTOR

    driver.find_element(By.CSS_SELECTOR, ".layout.layout-base")
    
  • 使用XPATH

    driver.find_element(By.XPATH, "//*[@class='layout layout-base']")
    

【讨论】:

    【解决方案2】:

    layout layout-base 是由空格分隔的两个类名值。
    要定位此元素,您可以使用以下任何一种方式:

    driver.find_element(By.CLASS_NAME,"layout.layout-base")
    

    或者

    driver.find_element(By.CSS_SELECTOR,"div.layout.layout-base")
    

    或者

    driver.find_element(By.XPATH,"//div[@class='layout layout-base']")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2011-12-13
      • 2011-11-07
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多