学习进度13

Selenium与chromediver的使用学习

demo1:

# webdriver.Chrome使用
# 获取driver.page_source
import time
from selenium import webdriver

# 驱动路径
driver_path = r"E:\pythonfile\chromedriver\chromedriver.exe"

# 创建驱动
driver = webdriver.Chrome(executable_path=driver_path)

driver.get(‘https://www.baidu.com/‘)

# 打印网页源代码
print(driver.page_source)

time.sleep(5)

# 关闭当前页面
driver.close()

# 关闭整个网页
driver.quit()

demo2:

# 定位元素

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

# 驱动路径
driver_path = r"E:\pythonfile\chromedriver\chromedriver.exe"

# 创建驱动
driver = webdriver.Chrome(executable_path=driver_path)

driver.get(‘https://www.baidu.com/‘)

# 通过id获取
# inputTag = driver.find_element_by_id(‘kw‘)
inputTag = driver.find_element(By.ID, ‘kw‘)   # 其他的原理一样

# 通过name获取
# inputTag = driver.find_element_by_name(‘wd‘)

# 通过class属性获取
# inputTag = driver.find_element_by_class_name(‘s_ipt‘)

# xpath语法获取
# inputTag = driver.find_element_by_xpath("//input[@id=‘kw‘]")

# CSS选择器
# inputTag = driver.find_element_by_css_selector(‘.quickdelete-wrap > input‘)

# 框框里输入java
inputTag.send_keys(‘java‘)

demo3:

# 操作表单元素

from selenium import webdriver
import time

# 驱动路径
driver_path = r"E:\pythonfile\chromedriver\chromedriver.exe"
# 创建驱动
driver = webdriver.Chrome(executable_path=driver_path)
driver.get(‘https://www.baidu.com/‘)

# 1.操作输入框
# inputTag = driver.find_element_by_id(‘kw‘)
# 输入
# inputTag.send_keys(‘java‘)
# time.sleep(5)
# 清除
# inputTag.clear()

# 2.check的话 同样获取
# click()就点亮 在click就灭了

# 3.Select的话 比较复杂
# selectBtn =Select(driver.find_element_by_id(‘kw‘))
# selectBtn.select_by_index(1)
# selectBin.select_by_values(url)
# selectBin.select_by_visible_text("名称")
# 取消选中
# selectTag.deselect_all()

# 4.按钮的点击事件
inputTag = driver.find_element_by_id(‘kw‘)
inputTag.send_keys(‘java‘)
submitTag = driver.find_element_by_id(‘su‘)
submitTag.click()

demo4:

# 网页中input在 ifame如何操作

from selenium import webdriver

# 驱动路径
driver_path = r"E:\pythonfile\chromedriver\chromedriver.exe"

# 创建驱动
driver = webdriver.Chrome(executable_path=driver_path)
driver.get("https://www.douban.com/")

# 找到iframe 因为我用的这个iframe是没有id和name的 因此需先xpath获取然后操作
iframe = driver.find_element_by_xpath("//div[@class=‘login‘]//iframe")

# 如果iframe 有id的话可直接替换
# driver.switch_to.frame(‘id属性值‘)
driver.switch_to.frame(iframe)
rememberBtn = driver.find_element_by_name(‘phone‘)
rememberBtn.send_keys(‘555‘)
# 释放回到当前主页面
driver.switch_to_default.content()

相关推荐