gpt4 book ai didi

javascript - Selenium 单击不会触发网站上的事件(python)

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:58:50 25 4
gpt4 key购买 nike

有时,当我使用 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。

我不确定并且真的很想弄清楚如何避免点击失败,特别是因为我认为我以 selenium 方式点击并等待。

最佳答案

问题是,如果当天的数据仍在加载,则点击不会转到第二天。换句话说,如果“加载微调器”可见 - 单击 > 按钮无效。

解决方法:等待包含微调器的 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'))
)

我对下一步按钮的操作也有点不同,请随意继续您自己的方法或切换到我的方法 - 关键修复在于等待“微调器”隐形。适合我。

关于javascript - Selenium 单击不会触发网站上的事件(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com