Python selenium

发布于:2024-04-29 ⋅ 阅读:(27) ⋅ 点赞:(0)

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()