Python selenium

1.搭建环境

1.安装:

复制代码
pip install msedge-selenium-tools

不要使用pip install selenium,我的电脑上没法运行

2.下载驱动

Microsoft Edge WebDriver |Microsoft Edge 开发人员

edge浏览器点设置---关于即可找到版本号,一定要下载对应版本的驱动

我的电脑是64位的,下载了x64的,但是运行时报错:OSError: [WinError 216] 该版本的 %1 与你运行的 Windows 版本不兼容。请查看计算机的系统信息,然后联系软件发布者。

下载win32的selenium解决

又报错:ValueError: Timeout value connect was <object object at 0x000001C609CC8630>, but it must be an int, float or None.

python selenium报错ValueError: Timeout value connect was <...>, but it must be an int, float or None._raise valueerror( valueerror: timeout value connec-CSDN博客

python selenium报错ValueError: Timeout value connect was <...>, but it must be an int, float or None._raise valueerror( valueerror: timeout value connec-CSDN博客

继续报错:ModuleNotFoundError: No module named 'urllib3.packages.six.moves'
复制代码
pip show selenium
Name: selenium
Version: 3.141.0
Summary: Python bindings for Selenium
Home-page: https://github.com/SeleniumHQ/selenium/
Author: UNKNOWN
Author-email: UNKNOWN
License: Apache 2.0
Location: C:\Users\15269\AppData\Local\Programs\Python\Python312\Lib\site-packages
Requires: urllib3
Required-by: msedge-selenium-tools

重装1.26.12的urllib3解决(我使用的是python3.12)如果还不行就多换几个试试

测试代码
复制代码
from msedge.selenium_tools import Edge, EdgeOptions

options = EdgeOptions()
options.use_chromium = True
options.add_experimental_option('excludeSwitches',['enable-automation'])  # 开启开发者模式
options.add_argument('--disable-blink-features=AutomationControlled')  # 禁用启用Blink运行时的功能
options.binary_location = r'C:\Program Files (x86)\Microsoft\EdgeCore\113.0.1774.50\msedge.exe'
url = 'https://www.baidu.com/'

driver = Edge(options=options, executable_path='./msedgedriver.exe')
driver.get(url)

二、带有用户数据的爬虫参考

以下内容转载自这位大佬的博客:

使用 Selenium 启动的 Chrome 浏览器,默认是无法使用本地数据的,如表单项、密码、Cookies 等。

原因分析

这是由于 Selenium 在启动 Chrome 时,默认将命令行参数 --user-data-dir(该参数用于设置用户数据目录)设为了一个"临时目录",如下图所示:

在 Selenium 启动的 Chrome 浏览器的地址栏中输出 chrome://version 并回车,就可以打开上图这个界面。

查看默认的用户数据目录的

手动 打开一个 Chrome 浏览器,在地址栏中输出 chrome://version 并回车,找到 Profile Path: 后面的路径,去掉最后的 \Default,就是默认的用户数据目录,它一般都是:C:\Users\Your_User_Name\AppData\Local\Google\Chrome\User Data

将默认的用户数据目录设为 Selenium 启动的 Chrome 的用户数据目录

代码如下:

复制代码
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

options = webdriver.ChromeOptions()
options.add_argument(r'user-data-dir=C:\Users\Your_User_Name\AppData\Local\Google\Chrome\User Data')
#  --user-data-dir 前的两个短杠似乎有没有均可

browser = webdriver.Chrome(
    options=options,
    service=Service()  # 需要将 Chrome 驱动放在此文件的同一目录下
)

browser.get('https://mail.163.com/')   # 此处以 163 邮箱为例,因为 163 邮箱的 Cookies 可以在本地保存 30 天。
time.sleep(120)

对于edge浏览器:edge://version/

三、实战应用

stm官网登录

登陆界面网址:登录注册 (stmicroelectronics.cn)

右键检查,找到用户名&密码&登录按钮的路径,并写出相应js代码。之后在控制台测试

复制代码
document.getElementById("username").value = "你的用户名"
document.getElementById("password").value = "你的密码"
document.querySelector(".an_lan").click() //登录

完整代码

复制代码
from msedge.selenium_tools import Edge, EdgeOptions




class Demo:
    def __init__(self) -> None:
        #keep alive为True,即处理完后不会关闭edge
        options = EdgeOptions()
        options.use_chromium = True
        options.add_experimental_option('excludeSwitches',['enable-automation'])  # 开启开发者模式
        #用户数据
        #options.add_argument(r'user-data-dir=C:\Users\15269\AppData\Local\Microsoft\Edge\User Data')

        options.add_argument('--disable-blink-features=AutomationControlled')  # 禁用启用Blink运行时的功能
        options.binary_location = r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'


        self.webdriver = Edge("./msedgedriver.exe", keep_alive=True, options=options)
        self.login_url = r"https://sso.stmicroelectronics.cn/User/LoginByPassword"
        self.username = "。。。"
        self.password = "@。。。"
    
    def login(self):
        payload = f"""
        document.getElementById("username").value = "{self.username}"
        document.getElementById("password").value = "{self.password}"
        document.querySelector(".an_lan").click() //登录
        """
        self.webdriver.get(self.login_url)
        self.webdriver.execute_script(payload)

    def run(self):
        self.login()


if __name__ == "__main__":
    Demo().run()
相关推荐
Once_day几秒前
研发效率破局之道阅读总结(4)个人效率
开发语言·研发效能·devops
痕517几秒前
如何在idea中写spark程序。
开发语言
神奇侠20249 分钟前
基于tabula对pdf中的excel进行识别并转换成word(三)
python·docx·tabula
LIUDAN'S WORLD17 分钟前
第五部分:进阶项目实战
图像处理·人工智能·python·opencv·计算机视觉·目标跟踪
禺垣25 分钟前
GBDT算法原理及Python实现
人工智能·python·算法·机器学习·数据挖掘·集成学习
谷雪_65828 分钟前
AIGC 落地实战:用 Stable Diffusion 打造企业级营销素材生成平台
python·stable diffusion·aigc
橙子1991101636 分钟前
请简述一下什么是 Kotlin?它有哪些特性?
android·开发语言·kotlin
martian6651 小时前
信创系统图形界面开发指南:技术选择与实践详解
开发语言·科技·系统架构·系统安全·创业创新
Scc_hy1 小时前
强化学习_Paper_2017_Curiosity-driven Exploration by Self-supervised Prediction
人工智能·python·深度学习·强化学习
我命由我123451 小时前
STM32 开发 - stm32f10x.h 头文件(内存映射、寄存器结构体与宏、寄存器位定义、实现点灯案例)
c语言·开发语言·c++·stm32·单片机·嵌入式硬件·嵌入式