Python与Selenium初试

来源:互联网 发布:平度市淘宝客服招聘网 编辑:程序博客网 时间:2024/06/06 02:18

1.安装Selenium for Python

找到Python的安装包,在Scripts\pip.exe文件夹下打开命令行,输入

pip.exe install selenium

2.第一脚本

下载了selenium for python后,可以尝试在python中输入如下代码:

from selenium import webdriverdriver = webdriver.Firefox()driver.get('http://www.baidu.com')driver.find_element_by_id('kw').send_keys('selenium')driver.find_element_by_id('su').click()

代码实现的功能是打开Firfox(),导航至百度网页,输入Selenium进行搜索。

运行上面的代码可能会出现类似下面的错误:

driver = webdriver.Firefox()Traceback (most recent call last):  File "<ipython-input-16-fd567e24185f>", line 1, in <module>    driver = webdriver.Firefox()  File "F:\Install\Python\Anaconda2\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 103, in __init__    self.binary, timeout)  File "F:\Install\Python\Anaconda2\lib\site-packages\selenium\webdriver\firefox\extension_connection.py", line 51, in __init__    self.binary.launch_browser(self.profile, timeout=timeout)  File "F:\Install\Python\Anaconda2\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 67, in launch_browser    self._start_from_profile_path(self.profile.path)  File "F:\Install\Python\Anaconda2\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 90, in _start_from_profile_path    env=self._firefox_env)  File "F:\Install\Python\Anaconda2\lib\subprocess.py", line 710, in __init__    errread, errwrite)  File "F:\Install\Python\Anaconda2\lib\subprocess.py", line 958, in _execute_child    startupinfo)WindowsError: [Error 2] 

最可能的出错原因是未在系统路径添加Firefox的安装路径,所以一种方法是将Firefox的安装路径添加到系统的Path中,另一种方法是在代码中显示声明:

from selenium import webdriverfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinarybinary = FirefoxBinary('path/to/binary')driver = webdriver.Firefox(firefox_binary=binary)

其中FirefoxBinary(‘path/to/binary’)是Firefox的安装路径,例如:
FirefoxBinary(‘C:/Users/myname/appdata/Local/Mozilla Firefox/firefox.exe’)

0 0
原创粉丝点击