使用Selenium向下滚动直到不可见元素变为可见

2024-04-18 06:36:43 发布

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

我想在页面上向下滚动,直到满足某个条件。 标准是最近可见足球比赛的日期早于参考日期。 我写了以下脚本:

from selenium import webdriver
from datetime import datetime
from time import sleep


if __name__ == '__main__':
   driver = webdriver.Chrome()
   driver.get('https://hdmatches.com/category/premier-league/')
   matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
   last_date = \
       matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
       -1].find_element_by_class_name('item-details').find_element_by_class_name(
       'td-module-meta-info').find_element_by_class_name('td-post-date').text
   last_date = datetime.strptime(last_date, '%B %d, %Y').date()
   start_season = datetime.strptime('2017-8-11', '%Y-%m-%d').date()

   while last_date > start_season:
      load_more = matches.find_element_by_xpath('//div[@class="td-load-more-wrap td-load-more-infinite-wrap"]')
      driver.execute_script("arguments[0].scrollIntoView();", load_more)
      matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
      last_date = \
          matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
          -1].find_element_by_class_name('item-details').find_element_by_class_name(
          'td-module-meta-info').find_element_by_class_name('td-post-date').text
      last_date = datetime.strptime(last_date, '%B %d, %Y').date()

我的脚本至今无法运行(什么都没有发生),我认为这是因为以下因素:

enter image description here

向下滚动时,在加载页面时,此元素将显示两次。之后,以下元素将加载页面:

enter image description here

请提供建议/帮助。非常感谢


Tags: namedivdatetimedatebydriverelementfind
1条回答
网友
1楼 · 发布于 2024-04-18 06:36:43

您可以滚动到页面底部,单击“加载更多”按钮并重复,直到找到日期。看起来比赛日期没有追溯到很久以前,你的赛季开始日期也没有达到,所以我把它改为一年后,它成功了。一、 另外,使用javascript单击LoadMore按钮是因为使用webdriver时有其他东西阻止了它。以下是代码更改:

start_season = datetime.strptime('2018-8-11', '%Y-%m-%d').date()

   while last_date > start_season:
      driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
      load_more = matches.find_element_by_xpath('//div[@class="td-load-more-wrap td-load-more-infinite-wrap"]')
      driver.execute_script("arguments[0].click();", load_more)
      matches = driver.find_element_by_xpath('//*[@id="td-outer-wrap"]/div[4]/div/div/div[1]')
      last_date = \
          matches.find_elements_by_xpath('//div[@class="td_module_10 td_module_wrap td-animation-stack"]')[
          -1].find_element_by_class_name('item-details').find_element_by_class_name(
          'td-module-meta-info').find_element_by_class_name('td-post-date').text
      last_date = datetime.strptime(last_date, '%B %d, %Y').date()

相关问题 更多 >