I want to use selenium to find a div:
My code is :
self.browser.find_element_by_xpath('//div[@]').click()
But I got the error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@]"}
What should I do to find this div?
CodePudding user response:
You can try changing the style value of the element to block using javascript.
self.driver.execute_script("document.getElementsByClassName("class-name")[0].style.display = 'block';")
Then try to access the element.
CodePudding user response:
Short:
Your xpath looks correct for the exampled page html, but the class on screenshot ends with the space char. (it could be the reason).
Longer:
If you getting NoSuchElementException
there can be 3 cases:
your div present in
iframe
, so you need to switch to iframe withdriver.switch_to.iframe
command before invoke find_element.you looking for div with the exact class match. class attribute sometimes changed after some actions, some classes could be added or removed. So, try to use
//div[contains(@class, 'your_class')]
. I see, your class ends with the space char on screenshot, it may affect.the element really not present on the page. Try to take screenshot, or print pagesource and look for the element, may be this will bring more information regarding the real reason.
CodePudding user response:
The DIV tag is a descendant of the A tag.
To click on the descendant DIV you can use either of the following Locator Strategies:
Using css_selector:
self.browser.find_element(By.CSS_SELECTOR, "a[href='#/sportVenueBookBC'] div.bh-headerBar-nav-item.").click()
Using xpath:
self.browser.find_element(By.XPATH, "//a[@href='#/sportVenueBookBC']//div[@class='bh-headerBar-nav-item ']").click()
However, the desired element is a dynamic element, so to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:
Using CSS_SELECTOR:
WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href='#/sportVenueBookBC'] div.bh-headerBar-nav-item."))).click()
Using XPATH:
WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@href='#/sportVenueBookBC']//div[@class='bh-headerBar-nav-item ']"))).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
References
You can find a couple of relevant discussions on NoSuchElementException in: