【问题标题】:web selenium testing can't locate element网络硒测试找不到元素
【发布时间】:2021-04-26 03:01:23
【问题描述】:

此代码应打开 flickr 网站并搜索“s”并单击从建议中搜索照片 但我给了我这个错误 "没有这样的元素:无法找到元素:{"method":"xpath","selector":"//span[contains(text(),'Search photos')]"} (会话信息:chrome=90.0.4430.85)"

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")

driver.get("https://www.flickr.com/")
#webdriver.support.wait.WebDriverWait(driver, 1)
driver.find_element_by_xpath("//input[@id='search-field']").send_keys("s")
webdriver.support.wait.WebDriverWait(driver, 1)
driver.find_element_by_xpath("//span[contains(text(),'Search photos')]").click()
webdriver.support.wait.WebDriverWait(driver, 1)

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    我认为初始化 WebDriverWait 有错误。

    要点击Search photos,请尝试使用.execute_script(..)method 和arguments[0].click(); 参数。

    试试下面的代码sn-p:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
    
    driver.get("https://www.flickr.com/")
    
    wait = WebDriverWait(driver, 20)
    
    search_field = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@id='search-field']")))
    search_field.send_keys("s")
     
    search_photos = wait.until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(),'Search photos')]")))
    driver.execute_script("arguments[0].click();", search_photos)
    

    【讨论】:

    • 谢谢。我不得不用 "search_photos = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@data-href='/search/?text=s']"))) search_photos 替换最后两行。 click()”,它现在工作了!
    • @EslamAshraf 是的,它适用于这种情况,但如果您更改 s 以外的搜索键,它将不起作用。
    • 是的,我知道这一点,但我认为这是唯一的解决方案,因为 chrome 不能接受另一行
    • @frianH 是对的。我最初的解决方案不是一个好的解决方案,当时我没有发现 data-ref 值是动态的,具体取决于您正在搜索的内容。这不是一个好的解决方案。我尝试用更可重复使用的东西替换它,但它不能始终如一地工作。我删除了我原来的回复。
    猜你喜欢
    • 2023-03-15
    • 2015-12-27
    • 2021-08-17
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多