[英]Python Selenium how to wait before clicking on link
I just wonder, how to have the browser wait before clicking on a link? 我只是想知道,在点击链接之前如何让浏览器等待? My goal is that I'm scraping from a dynamic webpage, the content is dynamic but I manage to get the form id. 我的目标是从动态网页上抓取内容,内容是动态的,但我设法得到表单ID。 The only problem is that the submit button is only displayed after 2-3 seconds. 唯一的问题是提交按钮仅在2-3秒后显示。 However, my Firefox driver start clicking on the link immediately when the page is loaded (not the dynamic part). 但是,我的Firefox驱动程序在加载页面时立即开始单击链接(而不是动态部分)。
Is there any way that I can make my browser wait 2-3 seconds until the submit button appears? 有什么方法可以让我的浏览器等待2-3秒,直到出现提交按钮? I tried to use time.sleep()
but it pauses everything, the submit button doesn't appear during time.sleep
but appears after 2-3 seconds when time.sleep
ends. 我尝试使用time.sleep()
但它暂停一切,提交按钮在time.sleep
期间不出现,但在time.sleep
结束后2-3秒后出现。
You can set wait like following : 您可以设置等待如下:
Explicit wait : 明确的等待 :
element = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.ID, "myElement"))
Implicit wait : 隐含等待:
driver.implicitly_wait(20) # seconds
driver.get("Your-URL")
myElement = driver.find_element_by_id("myElement")
You can use any of above. 您可以使用上述任何一种。 Both are valid. 两者都有效。
You need to use Selenium Waits
. 你需要使用Selenium Waits
。
In particular, element_to_be_clickable
expected condition is what fits better than others: 特别是, element_to_be_clickable
预期条件更适合其他条件:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "myDynamicElement"))
)
element.click()
where driver
is your webdriver instance, 10 is the amount of seconds to wait for an element. 其中driver
是您的webdriver实例,10是等待元素的秒数。 With this setup, selenium would try to locate an element every 500 milliseconds for 10 seconds in total. 通过这种设置,selenium将尝试每500毫秒定位一个元素,总共10秒。 It would throw TimeoutException
after 10 seconds left if element would not be found. 如果找不到元素,它会在10秒后抛出TimeoutException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.