[英]Locating element using Python Selenium
這是一個非常基本的示例,可通過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")
您也可以按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")))
請查閱以下文檔: 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.