【问题标题】:cant make selenium find element不能让硒找到元素
【发布时间】:2021-10-16 20:11:15
【问题描述】:

我试图通过 xpath 让 selenium 在这个 site 上找到一个元素(下面列表中的 1 个):

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(url)
driver.execute_script('window.scrollBy(0, 2000)')
folder = driver.find_element(By.XPATH,'//*[@id="__next"]/div[1]/main/div/div/div[3]/div/div[1]/div/div[3]/div[3]/div/div[2]/div[15]/button/div/div[2]/div/div/div/div[2]/span[2]/a')
print(folder)

但我得到一个错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="__next"]/div[1]/main/div/div/div[3]/div/div[1]/div/div[3]/div[3]/div/div[2]/div[15]/button/div/div[2]/div/div/div/div[2]/span[2]/a"}

我知道 react 制作的网站,但我没有设法获得该元素。 谢谢

【问题讨论】:

    标签: python html reactjs selenium


    【解决方案1】:

    为什么不使用 xpath 功能?

    //div[@role='listitem']//a[contains(@href,'assets')]
    

    右击节点并点击复制xpath没有用,你必须用xpath查询在元素中搜索

    folder = driver.find_element(By.XPATH,"//div[@role='listitem']//a[contains(@href,'assets')]")
    

    在使用 xpath 搜索之前检查页面中的所有元素是否已加载 (wait.until)

    【讨论】:

    • 谢谢,它起作用了(在添加了 2 秒的 time.sleep 之后 :))!您认为使用 selenium 是从该站点获取信息的最佳方式吗?
    • 也不要使用 time.sleep 并使用 webdriver 等待。
    【解决方案2】:

    从 PersianMans 的答案与 webdriver waits 相结合,您可以让您的程序等待元素存在。等等 10 秒。

    wait=WebDriverWait(driver, 10)
    url="https://opensea.io/collection/mekaverse?tab=activity&search%5BisSingleCollection%5D=true&search%5BeventTypes%5D%5B0%5D=AUCTION_CREATED"
    driver.get(url)
    folder=wait.until(EC.presence_of_element_located((By.XPATH,"//div[@role='listitem']//a[contains(@href,'assets')]")))
    print(folder)
    

    导入

    from selenium.webdriver.support.ui import WebDriverWait 
    from selenium.webdriver.support import expected_conditions as EC
    

    【讨论】:

      猜你喜欢
      • 2021-08-17
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多