简体   繁体   中英

Python Selenium finding element

I need your help for a strange problem. I am using Selenium library and I have problem with this instruction:

driver.find_element_by_name('longitude')

Sometimes it works and I can find the element with the name longitude and sometimes not even if nothing changes in the web page.

Use wait method before finding the element:- eg.

from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.support.ui import WebDriverWait

WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID,"element")))

使用time.sleep(seconds)加载页面,然后在您找到Web元素之后,有时如果页面未加载,它可能会像Web元素不可用一样抛出,因此请使用time.sleep()

You can implicit wait for that :

Something like :

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get("http://somedomain/url_that_delays_loading")
driver.find_element_by_name('longitude')

OR

Explicit wait :

WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.NAME,"longitude"))) 

For this you have to import these :

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC 

Please Note that you should not be mixing implicit wait with explicit wait , doing so can cause unpredictable wait time out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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