selenium调用Firefox和Chrome需要注意的一些问题,和出现的报错selenium:expected [object undefined] undefined to be a string

时间:2021-09-12 23:36:28

在高版本selenium下如:selenium3.4.3

1.高版本的selenium需要浏览器安装一些补丁驱动

Firefox:geckodriver
下载网址:http://download.csdn.net/detail/ztzy520/9725887 或https://github.com/mozilla/geckodriver/release
如:geckodriver-v0.14.0-win32
Chrome:chromedriver
下载网址:http://chromedriver.storage.googleapis.com/index.html
如:http://chromedriver.storage.googleapis.com/index.html?path=2.30/下
版本:chromedriver_win32.zip

2.直接将geckodriver和chromedriver放到浏览器的目录下

如geckodriver放到路径 C:\Program Files (x86)\Mozilla Firefox
如chromedriver放到路径 C:\Program Files (x86)\Google\Chrome\Application

3.调用方式

#方式一:设置火狐浏览器驱动(使用低于53.0版本火狐,如52.0.2,不然会报错selenium:expected [object undefined] undefined to be a string)
driver = webdriver.Firefox()
# 方式二:设置谷歌浏览器驱动
chromedriver = "C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)

4.具体测试代码(demo1.py):

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import os
#=====================================================================
# 方式一:设置火狐浏览器驱动
driver = webdriver.Firefox()
#=====================================================================
# 方式二:设置谷歌浏览器驱动
#chromedriver = "C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe"
#os.environ["webdriver.chrome.driver"] = chromedriver
#driver = webdriver.Chrome(chromedriver)
#=====================================================================
driver.get("http://www.baidu.com")
assert u"百度" in driver.title
elem = driver.find_element_by_name("wd")
elem.clear()
elem.send_keys(u"网络爬虫")
elem.send_keys(Keys.RETURN)
time.sleep(3)
assert u"网络爬虫." not in driver.page_source
driver.close()

selenium调用Firefox和Chrome需要注意的一些问题,和出现的报错selenium:expected [object undefined] undefined to be a string

注释:要解决调用火狐是出现"selenium:expected [object undefined] undefined to be a string"问题,需要将火狐的版本降低到53.0以下,如

52.0.2