在Python Splinter网络爬虫中设置超时

3 投票
2 回答
1823 浏览
提问于 2025-04-17 16:19

我想在Python中设置一个超时,就像在Ruby中那样。

我有一个链接,点击后会打开一个弹出窗口,但我无法访问这个窗口,因为它会导致脚本卡住,直到我强制结束它。我已经尝试了几个月想在Ruby的watir-webdriver中访问这个弹出窗口,但一直没有成功。

我想给弹出窗口的调用设置一个超时,然后再去访问这个弹出窗口。

@timeout(3)
try:
b.execute_script("javascript:openMdlWindow('InvestmentDetailOptions.aspx?IDAssetType=','620','600');if(window.document.RetValue == '2'){window.parent.LoadinIframe('InvestmentDetail.aspx?FromMenu=N&IDAssetType=','Investment Details > Full View','false');}")
except Exception, e:
print 'timeout!'

任何帮助都将非常感谢。

2 个回答

2

在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。比如说,当你在写代码时,可能会发现某个功能没有按照预期工作。这时候,你可能会去网上查找解决方案,比如在StackOverflow上提问或者寻找别人的回答。

在这些讨论中,大家会分享他们的经验和解决方法。有些人可能会提供代码示例,帮助你更好地理解如何解决问题。通过这些交流,你可以学到很多实用的技巧和知识。

总之,编程过程中遇到问题是很正常的,利用社区的力量来寻找答案,可以让你更快地进步。

import signal
from time import sleep

class TimeoutException(Exception):
    pass

def do_something_else():
    time = 5
    sleep(time)
    return 'do_something_else has to run for %d seconds' % time

def handler(signum, frame):
    raise TimeoutException 

def do_something_with_timeout(callback, timeout=3):
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(timeout)
    try:
        value = callback()
        signal.alarm(0)
        return value
    except TimeoutException:
        pass
    signal.signal(signal.SIGALRM, signal.SIG_IGN)
    return 'time out'

def main():
    print 'hello'
    print do_something_with_timeout(do_something_else)
    print 'world'

main()
6

你可以试试这个:

from splinter import Browser
from selenium.common.exceptions import TimeoutException
b = Browser('firefox')
b.driver.set_page_load_timeout(1)
try:
   b.visit('http://www.bbc.com')
except TimeoutException:
   pass
print b.html

撰写回答