我正在尝试通过多次单击展开按钮来抓取我需要展开项目列表的网页。
因此,当我研究如何以智能方式执行此操作时,我一直在尝试使用显式等待和预期条件(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)
如果我在点击它之前给予足够的睡眠但是我想让它更有效率。
答案 0 :(得分:0)
将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