简体   繁体   English

使用Python Selenium定位元素

[英]Locating element using Python Selenium

I'm new to Selenium, and I'm wondering how to locate the element highlighted in this image: 我是Selenium的新手,我想知道如何找到此图中突出显示的元素:

对象的HTML代码

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 未知错误:无法聚焦元素

Here is a very basic example to find an element by CSS Selector. 这是一个非常基本的示例,可通过CSS选择器查找元素。

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 您也可以按x路径查找

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")))

Please consult the documentation at: https://selenium-python.readthedocs.io/locating-elements.html 请查阅以下文档: 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. 我想向WebDriverWait.Until函数添加作为参数提供的预期条件(EC),以便代码暂停并有效地给页面提供一定的时间来加载可能在初始加载时不存在的元素。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM