提出问题
selenium的一些函数(例如.find_element_by_xpath等),在新版本的 selenium 4 中已经失效。
解决方式一:降级 selenium3
应当安装旧版本的selenium(3.141.0),程序才能正常运行。
具体操作如下:
1、 删除 urllib3 包: pip uninstall urllib3
2、 删除 selenium 包: pip uninstall selenium
期间如有询问,输入Y,回车
3、安装 urllib3:
pip install urllib3==1.25.8 -i https://pypi.tuna.tsinghua.edu.cn/simple
4、安装 selenium:
pip install selenium==3.141.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
5、查看已安装的版本:
pip show urllib3
pip show selenium
基本原理是:
我们要使用 selenium(版本3.141.0) 和 urllib3(版本1.25.8),是相匹配的1对。
如果版本不是这个,则先删除当前版本,再安装我们想要的版本。
其中urllib3是selenium的依赖包
解决方法二:使用 selenium4 的 API
彻底的解决方法,应该是更改自己的源程序,改掉那些失效的用法。适应新版本,也简化了安装。
具体做法如下:
增加2个引入
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
修改代码1
替换所有的(无s)
.find_element_by_xpath(改为
.find_element(By.XPATH,替换所有的(有s)
.find_elements_by_xpath(为
.find_elements(By.XPATH,替换所有的(无s)
.find_element_by_class_name(为
.find_element(By.CLASS_NAME,替换所有的(有s)
.find_elements_by_class_name(为
.find_elements(By.CLASS_NAME,其他查找方法与上面类似
即:
也就是
browser.find_element_by_xpath('//div[@id="main"]')
改成
browser.find_element(By.XPATH,'//div[@id="main"]')
参考:
https://blog.csdn.net/weixin_46279624/article/details/127076156