不使用驱动程序.刷新()?

2024-10-01 04:57:35 发布

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

我的目标是在网站发生变化时从中获取实时数据。 下面是一个URL示例: http://www.liveticker.com/spiel/6HXLRTtd/#spiel-statistiken;0

我使用python、selenium和time作为循环。虽然我对Firefox有点了解,但我想用PhantomJS(不要打开多个浏览器窗口),但是在刷新1-4次之后,它就不再刮了。在

我猜测为什么会这样:如果你手动访问页面,点击刷新几次,你会得到一条屏幕消息,告诉你刷新是不必要的。但这只是猜测,因为Firefox似乎仍然能够抓取数据。在

所以我想知道为什么PhantomJS停止了抓取,以及该怎么做。python是否有一种方法可以在不刷新或重新加载页面的情况下连续地获取实时数据(我猜是AJAX)?在

希望你能帮忙,我对这一切都很陌生,到目前为止还没有找到任何相关线索。在

以下是我的功能,以防万一:

def get_games_stats(url): 
  driver.get(url)
  t=2
  starttime=time.time()
  t=float(t)

  while True:
    time.sleep(t - ((time.time() - starttime) % t))
    driver.refresh()        
    time.sleep(5)

    tabelle = driver.find_element_by_id("tab-statistics-0-statistic")
    text_tabelle = tabelle.text
    x = text_tabelle.encode( "utf-8" )
    x= [int(s) for s in re.findall(r'\b\d+\b', x)]

    team_a =  x[::2]
    team_b = x[1::2]
    print team_a, team_b

Tags: 数据texturl目标gettimedriversleep
1条回答
网友
1楼 · 发布于 2024-10-01 04:57:35

正如您所提到的,有时页面刷新后可能会出现警报。这可能会阻止代码执行。请尝试按以下方式处理此警报:

from selenium.common.exceptions import NoAlertPresentException

while True:
    time.sleep(t - ((time.time() - starttime) % t))
    driver.refresh()        
    time.sleep(5)

    # This might not work with PhantomJS
    #try:
    #    driver.switch_to_alert().accept()
    #except NoAlertPresentException:
    #    pass

    try:
        driver.execute_script("window.confirm = function(msg) { return true; }")
    except:
        pass

    tabelle = driver.find_element_by_id("tab-statistics-0-statistic")
    text_tabelle = tabelle.text
    x = text_tabelle.encode( "utf-8" )
    x= [int(s) for s in re.findall(r'\b\d+\b', x)]

    team_a =  x[::2]
    team_b = x[1::2]
    print team_a, team_b

相关问题 更多 >