使用Python Selenium定位元素

时间:2019-03-04 20:59:16

标签: python css selenium

我是Selenium的新手,我想知道如何找到此图中突出显示的元素:

HTML code for object

这是我尝试过的方法,但是我收到以下错误消息:

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

未知错误:无法聚焦元素

2 个答案:

答案 0 :(得分:1)

这是一个非常基本的示例,可通过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")

您还可以通过x路径查找

webdriver.find_element_by_xpath('RELATIVE X PATH HERE')

在您的情况下,您似乎要等待该元素,因此可以执行此操作

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

答案 1 :(得分:0)

请查阅以下文档:https://selenium-python.readthedocs.io/locating-elements.html

我想向WebDriverWait.Until函数添加作为参数提供的预期条件(EC),以便代码暂停并有效地给页面留出一定的时间来加载初始时可能不存在的元素加载。

这是我过去使用的示例:

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)