【问题标题】:Cannot find the element on the web using selenium无法使用 selenium 在 Web 上找到该元素
【发布时间】:2021-11-13 02:06:26
【问题描述】:

我需要你的帮助。我正在使用 selenium 单击网页上的按钮,然后打开其他选项。不幸的是,它无法识别 Path 元素。网络模拟器是移动版,因为它更容易访问按钮(问题与桌面版相同)。我尝试点击网页上的其他按钮,它工作正常。

mobile_emulation = { "deviceName": "Galaxy S5" }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(chromedriver_path, options=chrome_options) 
driver.get('https://www...')

time.sleep(20)

Click1 = driver.find_element_by_xpath('//*[@id="header_3"]/div')
Click1.click()

错误是:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="header_3"]/div"}
  (Session info: chrome=93.0.4577.82)

网页代码图片如下:

感谢您的帮助!

【问题讨论】:

  • 欢迎来到 Stack Overflow。请添加导入以提供最小的可重现示例。

标签: python selenium selenium-webdriver web-scraping selenium-chromedriver


【解决方案1】:

试试

Click1 = driver.find_element_by_xpath('//div[@class="card-header"]')

Click1 = driver.find_element_by_id("header_3")

【讨论】:

    【解决方案2】:

    在 Selenium 中有 4 种点击方式。

    我将使用这个 xpath

    //div[contains(@id, 'header_3')]//div
    

    代码试用 1:

    time.sleep(5)
    driver.find_element_by_xpath("//div[contains(@id, 'header_3')]//div").click()
    

    代码试用 2:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@id, 'header_3')]//div"))).click()
    

    代码试用 3:

    time.sleep(5)
    button = driver.find_element_by_xpath("//div[contains(@id, 'header_3')]//div")
    driver.execute_script("arguments[0].click();", button)
    

    代码试用 4:

    time.sleep(5)
    button = driver.find_element_by_xpath("//div[contains(@id, 'header_3')]//div")
    ActionChains(driver).move_to_element(button).click().perform()
    

    进口:

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

    PS:如果我们在HTML DOM 中有唯一条目,请检查dev tools(谷歌浏览器)。

    检查步骤:

    Press F12 in Chrome -> 转到element 部分 -> 做一个CTRL + F -> 然后粘贴xpath 看看,如果你想要的element 得到突出显示

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2018-03-31
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 2014-07-13
      • 1970-01-01
      • 2019-10-26
      相关资源
      最近更新 更多