Selenium 无法定位元素

Selenium unable to locate the element

我不断收到这样的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div/div/div/div[2]/div/div/div/div[2]/div/div/form/input"}

我正在这个网站上工作,https://new.igashop.com.au/。我想要做的是从 google sheet 中提取我想要的城市并将其输入搜索栏,以便我可以访问该特定城市的网站。我找不到我的代码有什么问题。谁能给我任何建议?谢谢

driver = get_webdriver()
driver.delete_all_cookies()
driver.implicitly_wait(10)
driver.get("https://new.igashop.com.au/")
city = product_sheet.col_values(2)[index]
search_bar = driver.find_element_by_xpath('/html/body/div[2]/div/div/div/div[2]/div/div/div/div[2]/div/div/form/input')
search_bar.send_keys(city)
search_bar.send_keys(Keys.RETURN)

尝试复制 'full xpath' 并放置它而不是 xpath

search_bar = driver.find_element_by_xpath('

要将 字符序列 发送到您需要归纳的搜索字段 WebDriverWait for the and you can use either of the following :

  • 使用CSS_SELECTOR:

    driver.get("https://new.igashop.com.au/")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[aria-label='close modal'] > span[data-testid='icon-span-testId']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[data-testid='desktop-searchInputBox']"))).send_keys("Japan" + Keys.RETURN)
    
  • 使用XPATH:

    driver.get("https://new.igashop.com.au/")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@aria-label='close modal']/span[@data-testid='icon-span-testId']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-testid='desktop-searchInputBox']"))).send_keys("Japan" + Keys.RETURN)
    
  • 注意:您必须添加以下导入:

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

浏览器快照:

我假设您在正确获取城市名称方面没有问题。如果一切正常,则下面的代码可以在搜索字段中输入“城市名称”,然后单击它。

示例城市名称:“日本”

driver.find_element(By.ID, "desktop-searchInputBox").send_keys("Japan")
driver.find_element(By.CSS_SELECTOR, "#desktop-searchInputButton svg").click()

输出:

您在脚本中使用的 xpath 是绝对 xpath,并且很有可能在您执行脚本时发生变化。您应该使用相对稳定的 xpath。 还有一件事我注意到,当你打开这个网站时,一个弹出窗口用于打开,你必须在访问输入搜索框之前关闭它。

搜索这个xpath-

//input[@id='desktop-searchInputBox']