【问题标题】:How to apply Loop to working Python Selenium Script?如何将循环应用于工作 Python Selenium 脚本?
【发布时间】:2009-10-09 19:15:41
【问题描述】:

我正在尝试弄清楚如何将 for 循环应用于此脚本,但遇到了很多麻烦。我想遍历以 csv 格式存储的子域列表(即:一列有 20 个子域)并为每个子域打印 html。它们都具有相同的 SourceDomain。谢谢!

#Python 2.6
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.SourceDomain.com")
        self.selenium.start()

    def test_untitled(self):
        sel = self.selenium
        sel.open("/dns/www.subdomains.com.html")
        sel.wait_for_page_to_load("30000")
        html = sel.get_html_source()
        print html

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

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

【问题讨论】:

    标签: python list csv selenium loops


    【解决方案1】:
    #Python 2.6
    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.SourceDomain.com")
            self.selenium.start()
    
        def test_untitled(self):
            sel = self.selenium
            spamReader = csv.reader(open('your_file.csv'))
            for row in spamReader:
                sel.open(row[0])
                sel.wait_for_page_to_load("30000")
                print sel.get_html_source()
    
        def tearDown(self):
            self.selenium.stop()
            self.assertEqual([], self.verificationErrors)
    
    if __name__ == "__main__":
        unittest.main()
    

    顺便说一句,请注意没有必要将此脚本包装在 unittest 测试用例中。更好的是,你不需要硒来完成这么简单的任务(至少乍一看)。

    试试这个:

    import urllib2, csv
    
    def fetchsource(url):
        page = urllib2.urlopen(url)
        source = page.read()
        return source
    
    fooReader = csv.reader(open('your_file.csv'))
    for url in fooReader:
        print fetchsource(url)
    

    【讨论】:

    • 谢谢 - 我现在正在尝试测试您的第一个答案。我无法让 urllib2 工作,因为这些页面使用了很多 javaScript。为此,Alex Martelli 建议我使用 Selenium。
    • 我一直收到语法错误,因为我忘记了 (open('your_file.csv')) 上的第二个右括号:-P 它有效!谢谢!
    • 啊,这是您在瘦任务中使用 selenium 的小原因之一。很高兴看到它有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 2022-11-29
    相关资源
    最近更新 更多