【问题标题】:explicit wait on selenium on python在 python 上的 selenium 中显式等待
【发布时间】:2016-11-19 07:29:59
【问题描述】:

我正在尝试通过多次单击展开按钮来抓取需要展开项目列表的网页。

因此,当我研究如何以智能方式执行此操作时,我一直在尝试使用具有预期条件的显式等待 (element_to_be_clickable)。

这是我的测试代码:

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
import time

btn_xpath = '//*[@id="contents"]/div[1]/div[2]/div/div[1]'

browser = webdriver.Chrome('/Users/dongpark/Downloads/chromedriver')  # calling chrome driver from local folder
browser.get('http://cu.bgfretail.com/event/plus.do?category=event&depth2=1&sf=N')
wait = WebDriverWait(browser, 20)
time.sleep(8)


def check_exists_by_xpath(xpath):

    try:
        browser.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True


while True:

    button = check_exists_by_xpath(btn_xpath)

    if button is False:
        print "done"
        break
    else:
        print "more"
        wait.until(EC.element_to_be_clickable((By.XPATH, btn_xpath)))
        browser.find_element_by_xpath(btn_xpath).click()

check_exists_by_xpath 只是测试页面上的展开按钮是否仍然可用。

当我运行它时,我得到:

File "/Users/dongpark/Documents/kuk/firstSelenium/test.py", line 37, in <module>      browser.find_element_by_xpath(btn_xpath).click()
selenium.common.exceptions.WebDriverException: Message: unknown error: Element is not clickable at point (418, 920). Other element would receive the click: <div class="ico"></div>
  (Session info: chrome=54.0.2840.98)
  (Driver info: chromedriver=2.25.426935 (820a95b0b81d33e42712f9198c215f703412e1a1),platform=Mac OS X 10.12.0 x86_64)

如果我在点击之前给予足够的睡眠,它会起作用,但我想让它更有效率。

【问题讨论】:

    标签: javascript python selenium


    【解决方案1】:

    更改您的 check_exists_by_xpath 以等待元素出现:

    def check_exists_by_xpath(xpath):
    
      try:
          wait.until(EC.presence_of_element_located((By.XPATH, xpath))
      except NoSuchElementException:
          return False
    return True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2018-01-04
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多