Selenium自动化教程(一)环境搭建

MAC版环境搭建

Apple M1 Pro 终端运行 python3 -V 报错

xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

执行以下命令即可

xcode-select --install

python3 -V
查看python3版本号

Python 3.9.6

升级pip

python -m pip install --upgrade pip

配置全局国内镜像

pip config set global.index-url https://mirrors.aliyun.com/pypi/simple

CentOS7版环境搭建

centos8是自带python3的
centos7自带版本是python2.7

请参考以下链接,亲测

https://blog.csdn.net/xiaoxiaodechongzi/article/details/124397213


安装selenium库

  • 注意
  1. python3 支持pip和pip3
  2. 如果同时有python2和python3
    则pip作用于2,pip3作用于3
pip install selenium

安装谷歌浏览器及驱动

查看安装的谷歌浏览器版本
在中输入chrome://settings/help

在这里插入图片描述
找到对应版本,没有的话相近版本即可
在这里插入图片描述

驱动下载地址:

https://registry.npmmirror.com/binary.html?path=chromedriver/


基础案例

#!/usr/bin/python
# coding: UTF-8
# -*- coding:utf-8 -*-
# demo
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By


if __name__ == '__main__':
    url = 'https://www.baidu.com'
    text = '肥鱼'
    print('==========开始咯==========')
    service = Service(r'../util/chromedriver')
    # 启动chrome
    driver = webdriver.Chrome(service=service)
    try:
        driver.get(url)
        sleep(1)
        # 输入文本
        driver.find_element(By.XPATH, '//*[@id="kw"]').send_keys(text)
        # 点击
        confirm_btn = driver.find_element(By.XPATH,
                                          '//*[@id="su"]')
        driver.execute_script("arguments[0].click();", confirm_btn)
        sleep(1)
        # 打印
        res = driver.find_element(By.XPATH, '/html/body/div[2]/div[4]/div[1]/div[2]/div/div/div/div[2]/span').text
        print(res)
        sleep(10)
        print('==========已完成==========')
    except Exception as e:
        print('处理异常: %s' % str(e))
        print('=========异常中断==========')
    finally:
        # 关掉chrome进程
        driver.quit()

  • 点击使用的是js触发,原生点击方法会出现元素丢失,因为Z轴上有覆盖
  • 输入一般就用原生的就行,js的键入也是终极方案,后续会提到
  • XPATH查找元素,我最常用,因为简单,用起来太爽了

附录XPATH总结: 1、检查;2拷贝

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ssoul、肥鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值