Peter Chao
Peter Chao

Reputation: 443

Locating element using Python Selenium

I'm new to Selenium, and I'm wondering how to locate the element highlighted in this image:

HTML code for object

Here's what I've tried, but I get the error message below:

create_a_detector_btn = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"..)))

unknown error: cannot focus element

Upvotes: 0

Views: 103

Answers (2)

etherwar
etherwar

Reputation: 136

Please consult the documentation at: https://selenium-python.readthedocs.io/locating-elements.html

I like to add an expected condition (EC) provided as an argument to a WebDriverWait.Until function so that the code will pause and effectively give the page a certain amount of time to load an element that might not be present upon initial load.

Here's an example that I've used in the past:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException, TimeoutException

TIME_TIMEOUT = 10 # Ten-second timeout default

def eprint(*args, **kwargs):
    """ Prints an error message to the user in the console (prints to sys.stderr), passes
    all provided args and kwargs along to the function as usual. Be aware that the 'file' argument
    to print can be overridden if supplied again in kwargs.
    """
    print(*args, file=sys.stderr, **kwargs)

driver = webdriver.Chrome()
driver.get("https://web.site/page")

try:
    wait = WebDriverWait(driver, TIME_TIMEOUT).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".Select-placeholder")))

except NoSuchElementException as ex:
    eprint(ex.msg())

except TimeoutException as toex:
    eprint(toex.msg)

Upvotes: 0

Julian Silvestri
Julian Silvestri

Reputation: 2027

Here is a very basic example to find an element by CSS Selector.

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome() 
driver.get("URLHERE")
find_item = driver.find_element_by_css_selector("CSS SELECTOR HERE")

You can also find by x path

webdriver.find_element_by_xpath('RELATIVE X PATH HERE')

In your case it looks like you want to WAIT for the element so you can do this

element = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_css")))

Upvotes: 1

Related Questions