selenium简单使用

发布时间 2023-04-02 16:51:47作者: mlllily
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains
import time

# 加上参数 禁止chromedriver日志写屏
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])

# 创建webdriver对象,指明使用chrome浏览器驱动
wd = webdriver.Chrome(service=Service(r'/Users/llm/Desktop/chromedriver_mac_arm64/chromedriver'), options=options)
# 设置隐式等待
wd.implicitly_wait(10)

wd.get("https://login.fei.com")

"""
根据id选择元素,返回的是该元素对应的webElement对象
find_element会返回符合条件的第一个元素,没有符合条件的会报异常NoSuchElementException
"""
element = wd.find_element(By.ID, 'rc-tabs-0-tab-password')
element.click()

element2 = wd.find_element(By.NAME, 'tel')
element2.send_keys("1868127")

element2.clear()  # 清除输入框已有的字符
# get_attribute 可以用来获取元素的属性值, 下面是获取元素class属性的值
 print(element2.get_attribute("class"))

"""
获取html文本内容
"""
# 获取整个元素这一段的html文本内容
print(element2.get_attribute("outerHTML"))
# 获取元素内部的html文本内容
# print(element2.get_attribute("innerHTML"))
# 注意!输入框中的内容是不能通过element.text方式获取的,而是 获取元素的value属性
print(element2.get_attribute("value"))

element3 = wd.find_element(By.NAME, "current-password")
element3.send_keys("qwerty123")

element4 = wd.find_element(By.CLASS_NAME, "ant-checkbox-input")
element4.click()
element5 = wd.find_element(By.CLASS_NAME, "index_loginBtn__njGPI")
element5.click()

wd.find_element(By.CSS_SELECTOR, ".login-choose-school-role-item:nth-child(1)").click()
wd.find_element(By.CSS_SELECTOR, ".btn-primary").click()

wd.find_element(By.CLASS_NAME, "title_QeISv").click()
main_window = wd.current_window_handle

"""
寻找handle的一种方法
"""
# for handle in wd.window_handles:
#     wd.switch_to.window(handle)
#
#     if "Bing" in wd.title:
#         break

# 切换窗口句柄
wd.switch_to.window(wd.window_handles[1])

wd.find_element(By.CSS_SELECTOR, "div[class='card-container_1XUHw'] > div").click()
wd.switch_to.window(main_window)

wd.quit()