0


Selenium学习代码

入门

from selenium import webdriver
import time

# 如果报错找不到chromedriver,可以指定驱动程序路径:CHROMEDRIVER_PATH = r"C:\Users\...\chromedriver.exe"
# from selenium.webdriver import ChromeService
# from selenium.webdriver import FirefoxService
# service = ChromeService(executable_path=CHROMEDRIVER_PATH)
# driver = webdriver.Chrome(service=service, options=options)
# 创建一个driver对象,(如果chrome反爬,可以导入一个options对象)
# options = webdriver.ChromeOptions()
# driver = webdriver.Chrome(options)
# driver = webdriver.Chrome()

# 访问Firefox
driver = webdriver.Firefox()

# 打开网页
url = "https://www.baidu.com/"
driver.get(url)
time.sleep(5)
driver.quit()

元素定位

案例

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

driver = webdriver.Chrome()
driver.get("http://www.bilibili.com")
# 1.找到输入框的位置,输入软件测试
driver.find_element(By.CLASS_NAME, 'nav-search-input').send_keys("软件测试")
# 2.找到搜索框的位置,点击搜索
driver.find_element(By.CLASS_NAME, 'nav-search-btn').click()
time.sleep(3)
driver.close()

ID定位

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

driver = webdriver.Chrome()
# 窗口最大化
driver.maximize_window()
driver.get("http://www.baidu.com/")
# ID是唯一的,但如果网页ID不唯一也可以正常显示,只是只有第一个ID生效
# 许多网页不会展示ID
element = driver.find_element(By.ID, "kw").send_keys("欣欣爱学习")
driver.find_element(By.ID, "su").click()
sleep(3)
# driver.quit() selenium4 会自动检测关闭,selenium3不会
# driver.quit() 关闭全部浏览器窗口 driver.close() 关闭单个浏览器窗口

classname定位

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("http://www.bilibili.com")
# 1.找到输入框的位置,输入软件测试
# driver.find_element(By.CLASS_NAME, 'nav-search-input').send_keys("软件测试")
# 2.找到搜索框的位置,点击搜索
# driver.find_element(By.CLASS_NAME, 'nav-search-btn').click()
# driver.find_elements(By.CLASS_NAME, 'channel-link')[4].click()
for ele in driver.find_elements(By.CLASS_NAME, 'channel-link'):
    print(ele.text)

time.sleep(3)
driver.quit()

name定位

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

driver = webdriver.Chrome()
# 窗口最大化
driver.maximize_window()
driver.get("https://www.baidu.com/")
# driver.find_element(By.NAME, "wd").send_keys("欣欣爱学习")
driver.find_elements(By.NAME, "wd")[0].send_keys("欣欣爱学习")

time.sleep(3)
driver.quit()

tagname定位

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

driver = webdriver.Chrome()
# 窗口最大化
driver.maximize_window()
driver.get("http://www.bilibili.com/")
driver.find_element(By.TAG_NAME, "input").send_keys("欣欣爱学习")
# 不推荐使用elements寻找,太过繁琐
# driver.find_elements(By.TAG_NAME, "a")[50].click()

time.sleep(3)
driver.close()

link text定位

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.baidu.com/")
driver.find_element(By.LINK_TEXT, "新闻").click()
time.sleep(3)
driver.close()

partial link text定位

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.baidu.com/")
driver.find_element(By.PARTIAL_LINK_TEXT, "新").click()
# LINK_TEXT 和 PARTIAL_LINK_TEXT 只定位能点击的文本
time.sleep(3)
driver.close()

css_selector定位

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://baidu.com/")
# driver.get("https://www/bilibli.com/")

# css selector 定位在实际工作中经常使用
# ID前面需要加#
# driver.find_element(By.CSS_SELECTOR, "#kw").send_keys("欣欣")
# driver.find_element(By.CSS_SELECTOR, "#su").click()

# class name前面需要加.
# driver.find_element(By.CSS_SELECTOR, ".nav-search-input").send_keys("xin")

# name定位,'[name="wd"]' (外面里面不能同时用双引号)
# driver.find_element(By.CSS_SELECTOR, '[name="wd"]').send_keys("xin")

# 标签(TAG_NAME)属性定位
# driver.find_element(By.CSS_SELECTOR, "a[href='http://image.baidu.com/']").click()
# 模糊匹配-包含
# driver.find_element(By.CSS_SELECTOR, "a[href*='http://image.baidu.']").click()
# 模糊匹配-匹配开头
# driver.find_element(By.CSS_SELECTOR, "a[href^='http://image.bai']").click()
# 模糊匹配-匹配结尾
# driver.find_element(By.CSS_SELECTOR, "a[href$='image.baidu.com/']").click()
# 组合定位(下面是标签+classname)
# driver.find_element(By.CSS_SELECTOR, "input.s_ipt").send_keys("xin")

# 定位子元素
# driver.find_element(By.CSS_SELECTOR, "div#s-top-left>a").click()
# driver.find_element(By.CSS_SELECTOR, "div.s-top-left-new.s-isindex-wrap>a").click()
# driver.find_element(By.CSS_SELECTOR, "#s-top-left>a").click()
# driver.find_element(By.CSS_SELECTOR, "div#s-top-left>a:nth-child(3)").click()
# driver.find_elements(By.CSS_SELECTOR, "div#s-top-left>a")[4].click()
driver.find_element(By.CSS_SELECTOR, "div#s-top-left>a:first-child").click()

time.sleep(3)
driver.quit()

xpath定位

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://baidu.com/")
# 绝对路径,/为绝对路径
# driver.find_element(By.XPATH, "/html/body/div/div/div[3]/a").click()
# 根据ID定位,//为相对路径
# driver.find_element(By.XPATH, "//input[@id='kw']").send_keys("zzz")
# 根据class定位
# driver.find_element(By.XPATH, "//input[@class='s_ipt']").send_keys("zzz")
# 根据name定位
# driver.find_element(By.XPATH, "//input[@name='wd']").send_keys("zzz")
# 多个属性组合定位
# driver.find_element((By.XPATH, "//input[@name='wd' and @class='s_ipt")).send_keys("zzz")
# 多组数据使用下标定位
# driver.find_element(By.XPATH, '//div[@id="s-top-left"]/a[4]').click()
# 通过子元素找父元素
# driver.find_element(By.XPATH, '//div[@id="s-top-left"]/../div[3]').click()
# 通过同级找:弟弟元素:/following-sibling::a[2]  哥哥元素:/preceding-sibling::a[1]

time.sleep(3)
driver.close()

web模块定位

单选框radio

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.iviewui.com/view-ui-plus/component/form/radio")
# driver.find_elements(By.XPATH, '//input[@class="ivu-radio-input" and @type="radio"]')[1].click()
# time.sleep(2)
# driver.find_elements(By.XPATH, '//input[@class="ivu-radio-input" and @type="radio"]')[2].click()
# time.sleep(2)
# driver.find_elements(By.XPATH, '//input[@class="ivu-radio-input" and @type="radio"]')[3].click()
# driver.find_element(By.XPATH, '//span[text()="Android"]').click()
# time.sleep(2)
# driver.find_element(By.XPATH, '//span[text()="Windows"]').click()
driver.find_element(By.XPATH, '//span[text()="Android"]/preceding-sibling::span/input').click()

time.sleep(3)
driver.close()

CheckBox多选框

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.iviewui.com/view-ui-plus/component/form/checkbox")
# driver.find_element(By.XPATH, '//span[text()="香蕉"]').click()
# time.sleep(2)
# driver.find_element(By.XPATH, '//span[text()="苹果"]').click()
# time.sleep(2)
# driver.find_element(By.XPATH, '//span[text()="西瓜"]').click()
# driver.find_element(By.XPATH, '//span[text()="香蕉"]/preceding-sibling::span/input').click()

time.sleep(3)
driver.close()

select下拉框

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://sahitest.com/demo/selectTest.htm")
select = Select(driver.find_element(By.ID, "s1"))
time.sleep(1)
# 根据index的下标获取,从0开始
# select.select_by_index(1)
# 根据option的value进行选择
# select.select_by_value("51")
# 根据实际文本进行选择
# select.select_by_visible_text("Email")

# 有些网站的下拉框不是严格的select选择器,是普通的span框架,直接使用click()点击即可

time.sleep(3)
driver.close()

级联选择器

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.iviewui.com/view-ui-plus/component/form/cascader")
driver.find_element(By.XPATH, '//input[@class="ivu-input ivu-input-default"]').click()
driver.find_element(By.XPATH, '//li[contains(text(),"北京")]').click()
driver.find_element(By.XPATH, '//li[contains(text(),"故宫")]').click()

time.sleep(3)
driver.close()

日期选择器

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.iviewui.com/view-ui-plus/component/form/date-picker")
driver.find_element(By.XPATH, '//input[@class="ivu-input ivu-input-default ivu-input-with-suffix"]').send_keys("2023-10-15")
driver.find_elements(By.XPATH, '//input[@class="ivu-input ivu-input-default ivu-input-with-suffix"]')[1].send_keys("2023-10-15 - 2023-11-14")
time.sleep(3)
driver.close()

三种弹框(Alert、confirm、prompt)

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

driver = webdriver.Chrome()
driver.maximize_window()
# driver.get("https://sahitest.com/demo/alertTest.htm")
# driver.get("https://sahitest.com/demo/confirmTest.htm")
driver.get("https://sahitest.com/demo/promptTest.htm")

driver.find_element(By.NAME, "b1").click()
driver.switch_to.alert.send_keys("测试")
time.sleep(2)

# 使用alert.text获取按钮的文字
# print(driver.switch_to.alert.text)
# 点击确定
driver.switch_to.alert.accept()
# 点击取消
# driver.switch_to.alert.dismiss()
time.sleep(3)
driver.close()

文件上传upload

文件位于当前文件目录的file文件夹中,logo.txt

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

from practice_web.get_filepath import get_logo_path

path = get_logo_path()
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://sahitest.com/demo/php/fileUpload.htm")
# 获取input文件上传元素
upload = driver.find_element(By.ID, "file")
# 不推荐使用绝对路径,推荐使用相对路径:拼接文件路径
upload.send_keys(r"{}".format(path))
driver.find_element(By.NAME, "submit").click()
time.sleep(3)
driver.close()

获取文件相对路径get_logo_path()和download_file_path

import os

# __file__表示当前文件所在位置
def get_logo_path():
    path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "file", "logo.txt")
    return path

def download_file_path():
    path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "file")
    return path

print(get_logo_path())

if __name__ == '__main__':
    print(download_file_path())

文件下载

import os

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
# 绝对路径用//或\
from practice_web.get_filepath import download_file_path

path = download_file_path() + "/chromedriver_win32.zip"
if os.path.exists(path):
    os.remove(path)

chromeOptions = webdriver.ChromeOptions()
prefs = {"download.default_directory": "{}".format(download_file_path())}
chromeOptions.add_experimental_option("prefs",prefs)

driver = webdriver.Chrome(chromeOptions)
driver.maximize_window()
driver.get("http://chromedriver.storage.googleapis.com/index.html?path=2.0/")
time.sleep(3)
driver.find_element(By.XPATH, "/html/body/table/tbody/tr[7]/td[2]/a").click()
time.sleep(5)
driver.close()

iframe框架切换

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://sahitest.com/demo/iframesTest.htm")

driver.find_element(By.ID, "checkRecord").clear()
driver.find_element(By.ID, "checkRecord").send_keys("666")
# 用下标
driver.switch_to.frame(0)
driver.find_element(By.ID, "open-self").click()

time.sleep(3)
driver.close()
from selenium import webdriver
import time
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://sahitest.com/demo/iframesTest.htm")
# 打开本地的html文件,前面要加file://
# driver.get("file://C:/Users/14403/Desktop/pypycode/selecode/HTML/iframe_test.html")

# 进入iframe
# 用下标
# driver.switch_to.frame("iframe_id")
# 用name
# driver.switch_to.frame("iframe_name")
# driver.find_element(By.XPATH, "//span[text()='番剧']").click()
# 复制CSS_SELECTOR路径
ele = driver.find_element(By.CSS_SELECTOR, "body > iframe")
driver.switch_to.frame(ele)
driver.find_element(By.ID, 'open-self').click()

# 退出iframe,切换到上一级
# driver.switch_to.parent_frame()
# 切换到主界面
driver.switch_to.default_content()
driver.find_element(By.ID, "checkRecord").clear()
driver.find_element(By.ID, "checkRecord").send_keys("666")
time.sleep(4)
driver.close()

本地的HTML文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>IFRAME Tests</h2>

<input type="text" id="checkRecord" value="verify me"/><br/>
<input type="button" value="Click me" onclick="document.getElementById('checkRecord').value='1111'"/><br/>
<br/>

<iframe id="iframe_id" name="iframe_name" src="https://bilibili.com/" height="500px" style="float:left;margin:20px;">
</iframe>
</body>
</html>

web简单项目

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("http://sellshop.5istudy.online/sell/user/login_page")
# 输入账号
driver.find_element(By.ID, "username").send_keys("test13")
# 输入密码
driver.find_element(By.ID, "password").send_keys("123456")
# 点击登录
driver.find_element(By.CSS_SELECTOR, 'p[class="login button"]>input').click()
# 点击新增
driver.find_element(By.CSS_SELECTOR, 'a[href="/sell/seller/product/index"]').click()
# 输入名称
driver.find_element(By.NAME, "productName").send_keys("奶昔")
# 输入价格
driver.find_element(By.NAME, "productPrice").send_keys("15")
# 输入库存
driver.find_element(By.NAME, "productStock").send_keys(10)
# 输入描述
driver.find_element(By.NAME, "productDescription").send_keys("好好喝哦")
# 输入图片地址
driver.find_element(By.NAME, "productIcon").send_keys("https://img0.baidu.com/it/u=142016260,2279127701&fm=253&fmt=auto&app=138&f=JPG?w=500&h=750")
# 选择类目
select =Select(driver.find_element(By.NAME, "categoryType"))
select.select_by_value("33")
# 点击提交
driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click()
time.sleep(3)
driver.close()

本文转载自: https://blog.csdn.net/Good_Omens/article/details/133861868
版权归原作者 Good_Omens 所有, 如有侵权,请联系我们删除。

“Selenium学习代码”的评论:

还没有评论