selenium结合python学习
一定要注意版本,版本不符合可能无法打开
查看selenium版本
cmd,,python,,import selenium,,help(selenium),,使用enter换行,selenium版本2.53
get方法,打开页面,refresh刷新页面,time模块,time.sleep()等待时间,
查看页面元素,find_element_by_id,send_keys()方法用于输入文本
selenium中有18种元素定位方法,但是通过元素或xpath和css定位更加灵活,需要掌握其中一种
id定位:find_element_by_id()
name定位:find_element_by_name
class定位:find_element_by_class_name
tag定位:find_element_by_tag_name
link定位:find_element_by_link_text
partial_link定位:find_element_by_partial_link_text
xpath定位:find_element_by_xpath
css定位:find_element_by_css_selector
弹框
有3种类型:
alert(提醒,确认要这样操作吗?),
<input id = "alert" value = "alert" type = "button" onclick = "alert('您关注了yoyoketang吗?');"/>
confirm(是?否?),<input id = "confirm" value = "confirm" type = "button" onclick = "confirm('确定关注微信公众号:yoyoketang?');"/>
prompt(输入然后确认,也可以取消)
<input
id = "prompt" value = "prompt" type = "button" onclick = "var name =
prompt('请输入微信公众号:','yoyoketang'); document.write(name) "/>
都是用switch_to_alert方法切换(聚焦)到弹出框上
对alert弹框和coonfirm弹框的操作无非就是:获取文本text,确认accept()相当于点击确认按钮,关闭dismiss()相当于点击右上角的"x",输入(仅限于prompt)send_keys()
对prompt弹框还可以输入,send_keys()
# coding:utf-8
from selenium import webdriver
import time
url = "file:///C:/Users/wwx155675/Desktop/testalert.html"
driver = webdriver.Firefox()
driver.get(url)
driver.maximize_window()
time.sleep(4)
driver.find_element_by_id("alert").click()
time.sleep(3)
t = driver.switch_to_alert()
print t.text
t.accept()
针对这段代码需要注意的地方是:
首先# coding:utf-8
是必须要有的,说明了编码的形式,不然识别不了
其次,url的书写方式是有特点的,路径中的是"/",直接复制的windows路径是"\",要转换过来,开头是这个file:///
maximize_window()是有必要的,有时候浏览器默认按上次打开方式显示,导致窗口是小窗,有的东西显示不出来,导致页面校验错误
有一些页面也有弹窗,但不是所有弹窗都叫alert,alert弹出框界面比较简洁,靠这一点可以区分
<html>
<head>
<title>Alert</title>
</head>
<body>
<input id = "alert" value = "alert" type = "button" onclick = "alert('您关注了yoyoketang吗?');"/>
<input id = "confirm" value = "confirm" type = "button" onclick = "confirm('确定关注微信公众号:yoyoketang?');"/>
<input
id = "prompt" value = "prompt" type = "button" onclick = "var name =
prompt('请输入微信公众号:','yoyoketang'); document.write(name) "/>
</body>
</html>