Python 使用 Selenuim进行自动化点击入门,谷歌驱动,以百度为例

一、首先要下载谷歌驱动

1.(打开谷歌浏览器 - 设置 - 关于谷歌,查看谷歌浏览器版本,否则不对应无法调用,会提示:selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version xxxx)

2.下载对应版本谷歌webdrive,下面两个链接二选一

CNPM Binaries Mirror

Chrome for Testing availability

也可以在下发链接下载其他浏览器驱动(看你使用什么浏览器了):

https://www.selenium.dev/zh-cn/documentation/webdriver/troubleshooting/errors/driver_location/

把下载下来的 chromedriver.exe 文件复制到当前文件运行的目录下,或者放在其他地方,复制绝对路径使用一般不会出错。

3.cmd进入使用pip下载selenium

pip install selenium

4.代码部分示例

(复制Xpath方式可参考下图)

python 复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/11/21 10:30
# @Author : LanXiaoFang
# @Site : 
# @File : yzkd.py
# @Software: PyCharm


from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# option这里是你的chromedriver.exe的绝对路径替换进来
option = r"G:\works\PythonCharmPre\cnki_0116\chromedriver.exe"
url = "https://www.baidu.com/"  # 以百度为例,ulr中填你需要进行模拟点击的网址

option = webdriver.ChromeOptions()
# 此配置去掉浏览器正在受自动软件的监控
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# 模拟浏览器点击
option.add_argument(
    'user-agent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"')
# 设置信息
driver = webdriver.Chrome(options=option)
# 浏览器最大化,不放大有可能页面会兼容手机隐藏掉,之前小窗口老是xpath获取不到数据
driver.maximize_window()
# 打开chrome浏览器
driver.get(url)
# 网页打开要等待全部加载完才能获取到节点
time.sleep(5)

srk = driver.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[5]/div/div/form/span[1]/input")
srk.clear()  # 清空搜索栏
srk.send_keys("CSDN 懒笑翻")  # 设置搜索内容,这里可以自定义

bdyx = driver.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[5]/div/div/form/span[2]/input")
bdyx.click()

time.sleep(1500)  # 休息1500秒以有时间查看效果结果 可以删除或者设置短一些

time.sleep(5)
driver.quit()
相关推荐
LH_R17 小时前
OneTerm开源堡垒机实战(四):访问授权与安全管控
运维·后端·安全
Raymond运维17 小时前
MariaDB源码编译安装(二)
运维·数据库·mariadb
JuiceFS1 天前
从 MLPerf Storage v2.0 看 AI 训练中的存储性能与扩展能力
运维·后端
chen9452 天前
mysql 3节点mgr集群部署
运维·后端
LH_R2 天前
OneTerm开源堡垒机实战(三):功能扩展与效率提升
运维·后端·安全
dessler2 天前
Hadoop HDFS-高可用集群部署
linux·运维·hdfs
少妇的美梦2 天前
logstash教程
运维
chen9452 天前
k8s集群部署vector日志采集器
运维
chen9452 天前
aws ec2部署harbor,使用s3存储
运维
東雪蓮☆3 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs