显示时Python selenium单击元素

2024-04-26 20:57:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在抓取一个动态页面,需要用户点击“加载更多结果”按钮几次,以获得所有数据。有没有更好的方法来完成在显示时单击元素的任务?在

def clickon(xpath):
    try:
        element = driver.find_element_by_xpath(xpath)
    except:
        print "RETRYING CLICKON() for %s" % (xpath)
        time.sleep(1)
        clickon(xpath)
    else:
        element.click()
        time.sleep(3)

def click_element_while_displayed(xpath):
    element = driver.find_element_by_xpath(xpath)
    try:
        while element.is_displayed():
            clickon(xpath)
    except:
        pass

Tags: bytimedefdriver动态sleepelementfind
1条回答
网友
1楼 · 发布于 2024-04-26 20:57:52

我怀疑你问这个问题是因为目前的解决方案很慢。这主要是因为您有这些硬编码的time.sleep()延迟,它们等待的时间超过了通常应该等待的时间。为了解决这个问题,我开始使用Explicit Waits-初始化一个无休止的循环,并在selenium停止等待按钮可单击时中断循环:

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

wait = WebDriverWait(driver, 10)

while True:
   try:
       element = wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
       element.click()
   except TimeoutException:
       break  # cannot click the button anymore

   # TODO: wait for the results of the click action

现在最后一个TODO部分也很重要——在这里,我建议您等待一个特定的条件,该条件表明单击会导致页面上的某些内容,例如,加载了更多的结果。例如,可以使用类似于this one的自定义预期条件。在

相关问题 更多 >