selenium

129 阅读1分钟

未完成

环境搭建

python 环境搭建,

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

# 指定以手机模式打开
mobile_emulation = { "deviceName": "Nexus 5" }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
# driver = webdriver.Chrome( desired_capabilities = chrome_options.to_capabilities())

# 创建 WebDriver 对象,指明使用chrome浏览器驱动
# service=Service(r'e:\selenium\chromedriver.exe') 也可设置成环境变量,不写
wd = webdriver.Chrome(service=Service(r'e:\selenium\chromedriver.exe'))

# input()

# 调用WebDriver 对象的get方法 可以让浏览器打开指定网址
wd.get('https://www.baidu.com')
# wd.get('http://172.23.208.54:9005/#/Printing')
print('33')
wd.find_element(By.ID, 'kw').send_keys('byhy')

# wd.quit()



# 关闭chromedriver日志start
# from selenium import webdriver

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

# wd = webdriver.Chrome(options=options  # 这里指定 options 参数
# )
# 关闭chromedriver日志end`

selenium 语法

  • 查询器
from selenium.webdriver.common.by import By

wd.find_element(By.ID, 'username').send_keys('byhy')
wd.find_element(By.CLASS_NAME, 'password').send_keys('sdfsdf')
wd.find_element(By.TAG_NAME, 'input').send_keys('sdfsdf')
wd.find_element(By.CSS_SELECTOR,'button[type=submit]').click()

// 找所有的元素
wd.find_elements(By.CLASS_NAME,'animal')

element = wd.find_element(By.ID,'animal')
// 获取元素值
print(element.text)
print(element.get_attribute('class'))
element.get_attribute('innerHTML')
element.get_attribute('outerHTML')
print(element.get_attribute('value'))

find_element找到的是符合条件的第一个元素,若没有,则抛出NoSuchElementException异常。

find_elements找到的是符合条件的所有元素,若没有,则返回空列表