有时,当我使用selenium点击页面上的特定链接时,点击会通过,但网站不响应点击。例如,我尝试在nba.com上的统计页面上的日期之间导航时出现这种情况。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
import datetime
import time
def go_to_next_day(driver, next_date):
for elem in driver.find_elements_by_css_selector('.date-selector i'):
if 'right' in elem.get_attribute('class'):
print 'Found next day!'
elem.click()
break
else:
raise ValueError('Unable to navigate to the next day')
# wait 30 seconds until the next day loads
WebDriverWait(driver, 30).until(
ec.text_to_be_present_in_element((By.CSS_SELECTOR, '.date-selector > span'), next_date.strftime('%m/%d/%Y'))
)
if __name__ == '__main__':
# go to nba.com
driver = webdriver.Firefox()
driver.set_window_size(2560, 1600)
driver.get('http://stats.nba.com/scores/#!/10/03/2014')
print 'NBA.com loaded. Clicking to next day!!!'
end_date = datetime.datetime.now()
current_date = datetime.datetime.strptime('2014-10-03', '%Y-%m-%d')
# after page loads, just click right until you get to current date
while current_date <= end_date:
# do something interesting on the page, modeled as a sleep
time.sleep(1)
next_date = current_date + datetime.timedelta(days=1)
go_to_next_day(driver, next_date)
current_date = next_date
print 'Went to day {}'.format(current_date)
driver.quit()
print 'Done'
为什么脚本总是点击,但网站有时只更改其页面?是something to do with angular?我怀疑它与操作系统有什么关系,但我在Mac OS X上。
我不确定并且真的想弄清楚如何避免点击失败,特别是因为我认为我点击并以硒的方式等待。
答案 0 :(得分:3)
问题是,如果当前日期的数据仍在加载,则点击不会使其进入第二天。换句话说,如果&#34;加载微调器&#34;是可见的 - 点击&gt;按钮无效。
要解决它:等待包含微调器的div.loader
元素的隐身:
def go_to_next_day(driver, next_date):
wait = WebDriverWait(driver, 10)
actions = ActionChains(driver)
try:
next_button = wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, '.date-selector i[class*=right]')))
actions.move_to_element(next_button).click().perform()
except TimeoutException:
raise ValueError('Unable to navigate to the next day')
# THIS IS THE KEY FIX
wait.until(ec.invisibility_of_element_located((By.CSS_SELECTOR, "div.loader")))
# wait until the next day loads
wait.until(
ec.text_to_be_present_in_element((By.CSS_SELECTOR, '.date-selector > span'), next_date.strftime('%m/%d/%Y'))
)
我也使用下一个按钮进行操作有点不同,随时可以继续使用自己的方法或切换到我的方法 - 关键修复是在等待&#34;微调器&#34;隐形。适合我。