Can't get selenium to click button

两盒软妹~` 提交于 2021-02-10 12:42:34

问题


Pic of the website's inspect element More in Depth pic My Code snippet

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import requests
///
excel = driver.find_element_by_name('Excel')
excel.click()

I then get this when I try to run it, any help would be appreciated

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="Excel"]"}

回答1:


The desired element is a Angular element, so to click on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[mat-button] > span.mat-button-wrapper span"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@mat-button]/span[@class='mat-button-wrapper']//span[text()='Excel']"))).click()
    
  • Note: You have to add the following imports :

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



回答2:


driver.find_element_by_name('Excel') selects a tag with name='Excel'.

For example, it would find a tag like this:

<div name='Excel'>Hello</div>.

The CSS equivalent for find_element_by_name is [name="Excel"].

From the pic of your website's inspect element, it seems that you are trying to find an element with the text 'Excel' inside the div, so instead, you need to use the following function:

driver.find_element_by_link_text('Excel')

Hope that helped!

For more on Python selenium webdriver, use this link. It helped out a lot for me!



来源:https://stackoverflow.com/questions/63433544/cant-get-selenium-to-click-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!