我使用 selenium RC 循环浏览一长串 URL,依次将每个 URL 中的 HTML 写入 csv 文件。问题:由于 URL“30000ms 后超时”异常,程序经常在列表中的各个点退出。我没有在遇到 URL 超时时停止程序,而是尝试让程序简单地在 CSV 文件中写入超时注释(在 URL 的 HTML 已消失的行中)并移动转到列表中的下一个 URL。我试图在我的程序中添加一个“else”子句,但它似乎没有帮助(见下文)——即:程序每次超时时仍然会停止。即使当我使用 60000 毫秒的超时窗口打开 selenium-server 时,我似乎也会遇到 30000 毫秒的超时异常——例如:“java -jar selenium-server.jar -超时 600000”???

任何建议将不胜感激。谢谢。

from selenium import selenium
import unittest, time, re, csv, logging

class Untitled(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*firefox", "http://www.MainDomain.com")
        self.selenium.start()

    def test_untitled(self):
        sel = self.selenium
        spamReader = csv.reader(open('SubDomainList.csv', 'rb'))
        for row in spamReader:
            sel.open(row[0])
            sel.wait_for_page_to_load("400000")
            time.sleep(5)
            html = sel.get_html_source()
            ofile = open('output4001-5000.csv', 'ab')
            ofile.write(html + '\n')
            ofile.close
        else:
            ofile = open('outputTest.csv', 'ab')
            ofile.write("URL Timeout" + '\n')
            ofile.close

     def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
     unittest.main()
有帮助吗?

解决方案

请尝试以下操作:

from selenium import selenium
import unittest, time, re, csv, logging

class Untitled(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*firefox", "http://example.com")
        self.selenium.start()
        self.selenium.set_timeout("60000")

    def test_untitled(self):
        sel = self.selenium
        spamReader = csv.reader(open('SubDomainList.csv', 'rb'))
        for row in spamReader:
            try:
                sel.open(row[0])
            except Exception, e:
                ofile = open('outputTest.csv', 'ab')
                ofile.write("error on %s: %s" % (row[0],e))
            else:
                time.sleep(5)
                html = sel.get_html_source()
                ofile = open('output4001-5000.csv', 'ab')
                ofile.write(html.encode('utf-8') + '\n')
            ofile.close()

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
     unittest.main()

一些评论:

  • 打开后不需要 wait_for_page_to_load ,这会导致超时,因为一旦打开后加载页面,它将再次开始等待,并且页面将不会加载。
  • 大多数从 selenium 获得的失败(超时、未找到对象)都可以用 try- except 语句捕获
  • 您应该在测试中使用测试本身设置超时(使用 set_timeout ),这样它不依赖于您启动服务器的方式,它总是会等待您想要的时间
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top