2

使用 python 和 selenium 绑定在固定时间间隔上单击 javascript 生成的链接的正确方法应该是什么?它应该使用线程吗?

因为我需要继续处理输入数据,所以我需要刷新/重置计时器以继续接收数据,单击这个给定的链接进行刷新(这个链接是由 javascript 直接生成的 html)。

此致

4

1 回答 1

2

您不需要线程来执行此操作。

使用javascript函数setInterval连续点击链接。

例如:

import time

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://jsfiddle.net/falsetru/4UxgK/show/')

# Click the link every 3000 ms.
driver.execute_script('''
    // argument passed from Python can be accessed by `arguments` array.
    var link = arguments[0];
    var timer = setInterval(function() {
        link.click();
    }, 3000);
''', driver.find_element_by_id('activity'))

while True:
    data = driver.find_element_by_id('counter').text
    print(data)
    time.sleep(1)

笔记

如果您收到以下错误,请升级selenium到最新版本。我在使用Firefox 23.0 + selenium 2.32.0时遇到了以下错误。selenium 2.35.0错误消失了。

Traceback (most recent call last):
  File "t2.py", line 12, in <module>
    print driver.execute_script('''return 1 + 2;''')
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 397, in execute_script
    {'script': script, 'args':converted_args})['value']
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 165, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 158, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: u'waiting for evaluate.js load failed' ; Stacktrace: 
    at r (file:///tmp/tmpm1sJhH/extensions/fxdriver@googlecode.com/components/driver_component.js:8360)
    at fxdriver.Timer.prototype.runWhenTrue/g (file:///tmp/tmpm1sJhH/extensions/fxdriver@googlecode.com/components/driver_component.js:392)
    at fxdriver.Timer.prototype.setTimeout/<.notify (file:///tmp/tmpm1sJhH/extensions/fxdriver@googlecode.com/components/driver_component.js:386) 

替代方案:使用线程

import threading
import time

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://jsfiddle.net/falsetru/4UxgK/show/')

def click_loop(link, interval):
    while True:
        link.click()
        time.sleep(interval)

link = driver.find_element_by_id('activity')
threading.Thread(target=click_loop, args=(link, 3)).start()

while True:
    data = driver.find_element_by_id('counter').text
    print(data)
    time.sleep(1)
于 2013-09-09T10:24:07.443 回答