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

时间:2020-02-15 02:40:26

标签: python selenium

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

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

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

1 个答案:

答案 0 :(得分:0)

您可以滚动到页面底部,单击“加载更多”按钮,然后重复直到找到日期。看来比赛日期没有那么久远,您的开始赛季日期也没有兑现,所以我将其更改为一年后,它开始起作用。我也使用javascript单击“加载更多”按钮,因为还有其他使用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()