我一直在使用 urllib2 访问网页,但它不支持 javascript,所以我看了一下 Selenium,但即使阅读了它的文档我也很困惑。
我下载了用于 firefox 的 Selenium IDE 附加组件,并尝试了一些简单的操作。
from selenium import selenium
import unittest, time, re
class test(unittest.TestCase):
def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 4444, "*chrome", "http://www.wikipedia.org/")
self.selenium.start()
def test_test(self):
sel = self.selenium
sel.open("/")
sel.type("searchInput", "pacific ocean")
sel.click("go")
sel.wait_for_page_to_load("30000")
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
我只是访问 wikipedia.org 并在搜索字段中输入 pacific ocean,但是当我尝试编译它时,它给了我很多错误。
最佳答案
如果运行脚本导致 [Errno 111] Connection refused
错误,例如:
% test.py
E
======================================================================
ERROR: test_test (__main__.test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 11, in setUp
self.selenium.start()
File "/data1/unutbu/pybin/selenium.py", line 189, in start
result = self.get_string("getNewBrowserSession", [self.browserStartCommand, self.browserURL, self.extensionJs])
File "/data1/unutbu/pybin/selenium.py", line 219, in get_string
result = self.do_command(verb, args)
File "/data1/unutbu/pybin/selenium.py", line 207, in do_command
conn.request("POST", "/selenium-server/driver/", body, headers)
File "/usr/lib/python2.6/httplib.py", line 898, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py", line 935, in _send_request
self.endheaders()
File "/usr/lib/python2.6/httplib.py", line 892, in endheaders
self._send_output()
File "/usr/lib/python2.6/httplib.py", line 764, in _send_output
self.send(msg)
File "/usr/lib/python2.6/httplib.py", line 723, in send
self.connect()
File "/usr/lib/python2.6/httplib.py", line 704, in connect
self.timeout)
File "/usr/lib/python2.6/socket.py", line 514, in create_connection
raise error, msg
error: [Errno 111] Connection refused
----------------------------------------------------------------------
Ran 1 test in 0.063s
FAILED (errors=1)
那么解决方案很可能是您需要先运行 selenium 服务器。
在下载中SeleniumRC您会找到一个名为 selenium-server.jar 的文件(几个月前,该文件位于 SeleniumRC/selenium-server-1.0.3/selenium-server.jar
)。
在 Linux 上,您可以使用以下命令在后台运行 selenium 服务器
java -jar /path/to/selenium-server.jar 2>/dev/null 1>&2 &
您将找到有关如何设置服务器的更完整说明 here .
关于python - Python 中的 Selenium ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5198839/