我还未配置selenium,PhantomJS
- 00_访问页面
from selenium import webdriver
#browser = webdriver.PhantomJS() #无头浏览器
browser = webdriver.Chrome() # 谷歌浏览器
browser.get("http://www.baidu.com")
print(browser.page_source)
browser.close()
- 01_快速入门
# 导入 webdriver
from selenium import webdriver
# 要想调用键盘按键操作需要引入keys包
from selenium.webdriver.common.keys import Keys
import time
# 调用环境变量指定的PhantomJS浏览器创建浏览器对象
driver = webdriver.PhantomJS()
# get方法会一直等到页面被完全加载,然后才会继续程序,通常测试会在这里选择 time.sleep(2)
driver.get("http://www.baidu.com/")
time.sleep(2)
driver.execute_script("return document.body.scrollHeight")
# 获取页面名为 wrapper的id标签的文本内容
data = driver.find_element_by_id("wrapper").text
# 打印数据内容
print(data)
# 打印页面标题 "百度一下,你就知道"
print(driver.title)
# 生成当前页面快照并保存
driver.save_screenshot("./images/baidu.png")
# id="kw"是百度搜索输入框,输入字符串"长城"
driver.find_element_by_id("kw").send_keys("长城")
# id="su"是百度搜索按钮,click() 是模拟点击
driver.find_element_by_id("su").click()
time.sleep(2)
driver.execute_script("return document.body.scrollHeight")
# 获取新的页面快照
driver.save_screenshot("./images/qiku.png")
# 打印网页渲染后的源代码
print(driver.page_source)
print('============')
# 获取当前页面Cookie
print(driver.get_cookies())
# 清除输入框内容
driver.find_element_by_id("kw").clear()
print('============')
# 获取当前url
print(driver.current_url)
# 关闭当前页面,如果只有一个页面,会关闭浏览器
driver.close()
# 关闭浏览器
driver.quit()
- 02_单个元素查找
# 导入 webdriver
from selenium import webdriver
# 要想调用键盘按键操作需要引入keys包
from selenium.webdriver.common.keys import Keys
import time
# 调用环境变量指定的PhantomJS浏览器创建浏览器对象
driver = webdriver.PhantomJS()
# get方法会一直等到页面被完全加载,然后才会继续程序,通常测试会在这里选择 time.sleep(2)
driver.get("http://www.baidu.com/")
time.sleep(2)
driver.execute_script("return document.body.scrollHeight")
# 获取页面名为 wrapper的id标签的文本内容
data = driver.find_element_by_id("wrapper").text
# 打印数据内容
print(data)
# 打印页面标题 "百度一下,你就知道"
print(driver.title)
# 生成当前页面快照并保存
driver.save_screenshot("./images/baidu.png")
# id="kw"是百度搜索输入框,输入字符串"长城"
driver.find_element_by_id("kw").send_keys("长城")
# id="su"是百度搜索按钮,click() 是模拟点击
driver.find_element_by_id("su").click()
time.sleep(2)
driver.execute_script("return document.body.scrollHeight")
# 获取新的页面快照
driver.save_screenshot("./images/qiku.png")
# 打印网页渲染后的源代码
print(driver.page_source)
print('============')
# 获取当前页面Cookie
print(driver.get_cookies())
# 清除输入框内容
driver.find_element_by_id("kw").clear()
print('============')
# 获取当前url
print(driver.current_url)
# 关闭当前页面,如果只有一个页面,会关闭浏览器
driver.close()
# 关闭浏览器
driver.quit()
- 03_单个元素查找
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
browser.get("http://www.taobao.com")
input_first = browser.find_element(By.ID,"q")
print(input_first)
browser.close()
- seleniumtest_04_多个元素查找
from selenium import webdriver
# 获取商品分类
browser = webdriver.Chrome()
browser.get("https://www.taobao.com")
lis = browser.find_elements_by_css_selector('.service-bd li')
print(len(lis))
li_list = browser.find_elements_by_tag_name('li')
print(len(li_list))
class_list = browser.find_elements_by_class_name('service-bd')
print(len(class_list))
xpath_list = browser.find_elements_by_xpath('//div[@class="service J_Service"]')
print(len(xpath_list))
linktext_list = browser.find_elements_by_link_text('美妆')
print(len(linktext_list))
browser.close()
- seleniumtest_05_获取元素属性
from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
logo = browser.find_element_by_id('zh-top-link-logo')
print(logo)
print(logo.get_attribute('class'))
print(logo.get_attribute('data-za-c'))
print(logo.get_attribute('data-za-a'))
print(logo.get_attribute('data-za-l'))
print(logo.get_attribute('href'))
print(logo.get_attribute('id'))
browser.close()
- seleniumtest_06_获取文本值
from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.text)
- seleniumtest_07_获取ID,位置,标签名
from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.id)
print(input.tag_name)
print(input.location)
print(input.size)
- seleniumtest_08_执行JavaScript
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("http://www.zhihu.com/explore")
print(browser.page_source)
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
browser.execute_script('alert("To Bottom")')
- seleniumtest_09_获取cookie
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("http://www.zhihu.com/explore")
print(browser.page_source)
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
browser.execute_script('alert("To Bottom")')
- seleniumtest_10_添加cookie
from selenium import webdriver
driver = webdriver.Chrome()
# driver.get("http://member.rltxtest.xyz/login/login.html")
driver.get ("http://www.youdao.com")
# 向cookie中name和value中添加回话信息,
driver.add_cookie({'name': 'key-aaaaaaa','value': 'value-bbbbb'})
# 遍历cookie中name和value信息并打印对应的信息,并包括添加对应的信息
for cookie in driver.get_cookies():
print("%s->%s" % (cookie['name'], cookie['value']))
driver.quit ()
- seleniumtest_11_案例:截屏
from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://blog.csdn.net/Kwoky/article/details/80285201")
driver.save_screenshot("./images/app2.png")
- seleniumtest_12_案例:超长屏截取
from selenium import webdriver
br = webdriver.Chrome()
#br.maximize_window()
br.get("http://jwgl.xxu.edu.cn/")
br.save_screenshot("./images/app1.png")
- seleniumtest_13_模拟点击
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/clicks.htm')
click_btn = driver.find_element_by_xpath('//input[@value="click me"]') # 单击按钮
doubleclick_btn = driver.find_element_by_xpath('//input[@value="dbl click me"]') # 双击按钮
rightclick_btn = driver.find_element_by_xpath('//input[@value="right click me"]') # 右键单击按钮
ActionChains(driver).click(click_btn).double_click(doubleclick_btn).context_click(rightclick_btn).perform() # 链式用法
print(driver.find_element_by_name('t2').get_attribute('value'))
sleep(10)
driver.quit()
- seleniumtest_14_鼠标移动
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/mouseover.htm')
write = driver.find_element_by_xpath('//input[@value="Write on hover"]') # 鼠标移动到此元素,在下面的input框中会显示“Mouse moved”
blank = driver.find_element_by_xpath('//input[@value="Blank on hover"]') # 鼠标移动到此元素,会清空下面input框中的内容
result = driver.find_element_by_name('t1')
action = ActionChains(driver)
sleep(5)
action.move_to_element(write).perform() # 移动到write,显示“Mouse moved”
print(result.get_attribute('value'))
sleep(5)
action = ActionChains(driver)
# action.move_to_element(blank).perform()
action.move_by_offset(10, 50).perform() # 移动到距离当前位置(10,50)的点,与上句效果相同,移动到blank上,清空
print(result.get_attribute('value'))
sleep(5)
action = ActionChains(driver)
action.move_to_element_with_offset(blank, 10, -40).perform() # 移动到距离blank元素(10,-40)的点,可移动到write上
print(result.get_attribute('value'))
sleep(5)
driver.quit()
- seleniumtest_15_拖拽
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/dragDropMooTools.htm')
dragger = driver.find_element_by_id('dragger') # 被拖拽元素
item1 = driver.find_element_by_xpath('//div[text()="Item 1"]') # 目标元素1
item2 = driver.find_element_by_xpath('//div[text()="Item 2"]') # 目标2
item3 = driver.find_element_by_xpath('//div[text()="Item 3"]') # 目标3
item4 = driver.find_element_by_xpath('//div[text()="Item 4"]') # 目标4
sleep(5)
action = ActionChains(driver)
action.drag_and_drop(dragger, item1).perform() # 1.移动dragger到目标1
sleep(5)
action = ActionChains(driver)
action.click_and_hold(dragger).release(item2).perform() # 2.效果与上句相同,也能起到移动效果
sleep(5)
action = ActionChains(driver)
action.click_and_hold(dragger).move_to_element(item3).release().perform() # 3.效果与上两句相同,也能起到移动的效果
sleep(5)
action = ActionChains(driver)
action.drag_and_drop_by_offset(dragger, 400, 150).perform() # 4.移动到指定坐标
#action.click_and_hold(dragger).move_by_offset(400, 150).release().perform() # 5.与上一句相同,移动到指定坐标
sleep(5)
driver.quit()
- seleniumtest_16_按键
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# 要想调用键盘按键操作需要引入keys包
from selenium.webdriver.common.keys import Keys
from time import sleep
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/keypress.htm')
key_up_radio = driver.find_element_by_id('r1') # 监测按键升起
key_down_radio = driver.find_element_by_id('r2') # 监测按键按下
key_press_radio = driver.find_element_by_id('r3') # 监测按键按下升起
enter = driver.find_elements_by_xpath('//form[@name="f1"]/input')[1] # 输入框
result = driver.find_elements_by_xpath('//form[@name="f1"]/input')[0] # 监测结果
sleep(3)
# 监测key_down
key_down_radio.click()
ActionChains(driver).key_down(Keys.CONTROL, enter).key_up(Keys.CONTROL).perform()
print(result.get_attribute('value'))
sleep(3)
# 监测key_up
key_up_radio.click()
enter.click()
ActionChains(driver).key_down(Keys.SHIFT).key_up(Keys.SHIFT).perform()
print(result.get_attribute('value'))
sleep(3)
# 监测key_press
key_press_radio.click()
enter.click()
ActionChains(driver).send_keys('a').perform()
print(result.get_attribute('value'))
sleep(3)
driver.quit()
*seleniumtest_17_下拉框的处理
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from time import sleep
driver = webdriver.Chrome()
driver.get('http://sahitest.com/demo/selectTest.htm')
sleep(3)
s1 = Select(driver.find_element_by_id('s1Id')) # 实例化Select
s1.select_by_index(1) # 选择第二项选项:o1
print(s1.first_selected_option.text)
sleep(3)
s1.select_by_value("o2") # 选择value="o2"的项
print(s1.first_selected_option.text)
sleep(3)
s1.select_by_visible_text("o3") # 选择text="o3"的值,即在下拉时我们可以看到的文本
print(s1.first_selected_option.text)
sleep(3)
driver.quit()
- seleniumtest_18_弹窗处理
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://sahitest.com/demo/alertTest.htm")
time.sleep(3)
driver.find_element_by_name("b1").click()
#time.sleep(3)
al = driver.switch_to_alert()
time.sleep(3)
al.accept()
time.sleep(3)
driver.close()
- seleniumtest_19_页面前进和后退
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.implicitly_wait(3) # seconds
first_url = 'http://www.baidu.com/'
driver.get(first_url)
print(driver.title) # 第一个页面
driver.find_element_by_link_text("新闻").click()
#driver.switch_to_window(driver.window_handles[0])
print(driver.title) # 第一个页面
#browser.switch_to_window(browser.window_handles[1])
#browser.title # 最后一个页面
time.sleep(2)
driver.back() # 从百度新闻后退到百度首页
print(driver.title) # 第一个页面
time.sleep(2)
driver.forward() # 百度首页前进到百度新闻
print(driver.title) # 第一个页面
time.sleep(2)
driver.quit()
- seleniumtest_20_选项卡管理
import time
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.execute_script('window.open()')
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])
browser.get('https://www.taobao.com')
time.sleep(1)
browser.switch_to_window(browser.window_handles[0])
browser.get('https://python.org')
- seleniumtest_21_ifram
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.maximize_window()
# get方法会一直等到页面被完全加载,然后才会继续程序,通常测试会在这里选择 time.sleep(2)
driver.get("http://sahitest.com/demo/iframesTest.htm")
time.sleep(2)
print(driver.current_url)
print(driver.page_source)
frames = driver.find_elements_by_tag_name("iframe")
driver.switch_to_frame(frames[0])
print('================================================')
print(driver.page_source)
print(driver.current_url)
- seleniumtest_22_显式等待
from selenium import webdriver
from selenium.webdriver.common.by import By
# WebDriverWait 库,负责循环等待
from selenium.webdriver.support.ui import WebDriverWait
# expected_conditions 类,负责条件触发
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
wait = WebDriverWait(driver, 10)
try:
# 页面一直循环,直到 id="myDynamicElement" 出现
element = wait.until(
EC.presence_of_element_located((By.ID, "su"))
)
finally:
driver.quit()
- seleniumtest_23_隐式等待懒加载模式无头模式
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10) # seconds
driver.get("http://www.baidu.com")
myDynamicElement = driver.find_element_by_id("su")
driver.quit()
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver import Chrome,PhantomJS
from selenium import webdriver
desired_capabilities = DesiredCapabilities.CHROME # 懒加载模式
desired_capabilities["pageLoadStrategy"] = "none"
chrome_options = webdriver.ChromeOptions() # 无头模式
chrome_options.add_argument("--headless")
driver = Chrome(desired_capabilities=desired_capabilities,chrome_options=chrome_options)
wait = WebDriverWait(driver, 20) # 等待20秒超时
driver.get(FEATURE)
wait.until(EC.presence_of_element_located((By.XPATH, "//title"))) #获取到该元素
driver.execute_script("window.stop();") # 停止刷新该页面
- seleniumtest_24_代理ip设置
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=http://171.37.135.94:8123')
driver = webdriver.Chrome(chrome_options=chrome_options)
小练习
登陆人人网
from urllib import request
from urllib import parse
import http.cookiejar
filename = './data/renrencookie.txt'
# 1. 构建一个CookieJar对象实例来保存cookie
cookie = http.cookiejar.MozillaCookieJar(filename,delayload=1)
# 2. 使用HTTPCookieProcessor()来创建cookie处理器对象,参数为CookieJar()对象
cookie_handler = request.HTTPCookieProcessor(cookie)
# 3. 通过 build_opener() 来构建opener
opener = request.build_opener(cookie_handler)
# 4. addheaders 接受一个列表,里面每个元素都是一个headers信息的元祖, opener将附带headers信息
opener.addheaders = [("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36")]
# 5. 需要登录的账户和密码
data = {"email":"user", "password":"password"}
# 6. 通过urlencode()转码
postdata = parse.urlencode(data).encode(encoding='UTF-8')
#print(postdata)
# 7. 构建Request请求对象,包含需要发送的用户名和密码
req = request.Request("http://www.renren.com/PLogin.do", data = postdata)
# 8. 通过opener发送这个请求,并获取登录后的Cookie值,
opener.open(req)
#5. 保存cookie到本地文件
print(type(cookie))
for item in cookie:
print(item.name + "=" + item.value)
cookie.save(ignore_discard=True,ignore_expires=True)
# 9. opener包含用户登录后的Cookie值,可以直接访问那些登录后才可以访问的页面
response = opener.open("http://www.renren.com/966924492/")
# 10. 打印响应内容
print(response.read().decode())
哈哈哈!蒙了吧,自己找项目练习去