简体   繁体   English

Python Selenium:如何从页面获取新数据定期刷新?

[英]Python Selenium: How to get fresh data from the page get refreshed periodically?

I have already written a script that opens Firefox with a URL, scrape data and close. 我已经编写了一个脚本,用URL打开Firefox,抓取数据并关闭。 The page belongs to a gaming site where page refresh contents via Ajax. 该页面属于游戏站点,其中页面通过Ajax刷新内容。

Now one way is to fetch those AJAX requests and get data or refresh page after certain period of time within open browser. 现在,一种方法是在打开的浏览器中获取那些AJAX请求并在一段时间后获取数据或刷新页面。

For the later case, how should I do? 对于后一种情况,我该怎么办? Should I call the method after certain time period or what? 我应该在一段时间后调用该方法还是什么?

You can implement so-called smart wait . 您可以实现所谓的smart wait

  1. Indicate the most frequently updating and useful for you web element at the page 在页面上指出最常更新和对您有用的Web元素
  2. Get data from it by using JavaScript since DOM model will not be updated without page refresh, eg: 使用JavaScript从中获取数据,因为如果没有页面刷新,DOM模型将不会更新,例如:

    driver.execute_script('document.getElementById("demo").innerHTML')

  3. Wait for certain time, get it again and compare with previous result. 等待一段时间,再次获取并与之前的结果进行比较。 If changed - refresh page, fetch data, etc. 如果更改 - 刷新页面,获取数据等。

You can use the time library to do it. 您可以使用时间库来执行此操作。 For example: 例如:

import time
from selenium import webdriver

driver = webdriver.Firefox()

while <condicion>:
  driver.get("http://www.url.org")
  # extract and save data
  time.sleep(5000) # whaits 5000 seconds

driver.close()

Make sure to call findElement() again after waiting, bc otherwise you might not get a fresh instance. 确保在等待后再次调用findElement() ,否则你可能无法获得新的实例。 Or use page factory, which will get a fresh copy of the WebElement for you every time the instance is accessed. 或者使用页面工厂,每次访问实例时都会为您获取WebElement的新副本。

Try with refresh the page time by time to get the updated result. 尝试逐页刷新页面以获取更新的结果。

  driver.navigate().refresh();

To refresh page in a period of time refer below link :- 要在一段时间内刷新页面,请参阅以下链接: -

Running a python script for a user-specified amount of time? 在用户指定的时间内运行python脚本?

Hope it will help you :) 希望它能帮到你:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM