#与页面交互 ''' <input type="text" name="passwd" id="passwd-id" /> ------------------ element = driver.find_element_by_id("passwd-id") element = driver.find_element_by_name("passwd") element = driver.find_element_by_xpath("//input[@id='passwd-id']") 使用`XPATH`时,你必须注意,如果匹配超过一个元素,只返回第一个元素。 如果上面也没找到,将会抛出 ``NoSuchElementException``异常 '''
#填写表格
#切换下拉框 寻找页面第一个 “SELECT” 元素, 并且循环他的每一个OPTION元素, 打印从utamen的值,然后按顺序都选中一遍
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://www.python.org")
assert driver.title("Python")
element = driver.find_element_by_xpath("//select[@name='name']")
all_options = element.find_element_by_tag_name("option")
for option in all_options:
print("Value is: %s" % option.get_attribute("value"))
option.click()
#WebDriver的支持类包括一个叫做 ``Select``的类,提供有用的方法处理这些内容:
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_tag_name('name'))
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)
#取消选择已经选择的元素:
select = Select(driver.find_element_by_id('id'))
select.deselect_all()
#列出所有已经选择的选项
select = Select(driver.find_element_by_xpath("xpath"))
all_selected_options = select.all_selected_options
#获得所有选项
options = select.options
#提交 Assume the button has the ID "submit" :)
driver.find_element_by_id("submit").click()
#WebDriver对每一个元素都有一个叫做 “submit” 的方法,如果你在一个表单内的 元素上使用该方法,
# WebDriver会在DOM树上就近找到最近的表单,返回提交它。
# 如果调用的元素不再表单内,将会抛出``NoSuchElementException``异常:
element.submit()
#拖放 使用拖放,无论是移动一个元素,或放到另一个元素内:
element = driver.find_element_by_tag_name("source")
target = driver.find_element_by_tag_name("target")
from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()
# WebDriver 支持在不同的窗口之间移动,只需要调用``switch_to_window``方法即可:
driver.switch_to_window("window_name")
# 如何查看 driver指向的当前窗口,查看javascript或者连接代码:
# <a href="somewhere.html" target="windowName">Click here to open a new window</a>
#迭代 所有打开的窗口
for handle in driver.window_handles:
driver.switch_to_window(handle)
#不同的frame 切换
driver.switch_to_frame("frameName")
# 用 “.” 还可以获取子frame,并通过下标指定任意frame,
driver.switch_to_frame("frameName.0.child")
#完成frame中的工作,返回父frame:
driver.switch_to_default_content()
#处理弹出对话框 某些动作之后可能会触发弹出对话框,访问对话框
alert = driver.switch_to_alert()
#它将返回当前打开的对话框对象。使用此对象,您现在可以接受、排除、读取其内容,
# 甚至可以在prompt对话框中输入(xxx)
# 这个接口对alert, confirm, prompt 对话框效果相同。
#访问浏览器历史记录
# 打开一个页面
driver.get("http://www.example.com")
#在浏览历史中前进和后退你可以使用:
driver.forward()
driver.back()
#操作Cookies
# 打开一个页面
driver.get("http://www.example.com")
# 现在设置Cookies,这个cookie在域名根目录下(”/”)生效
cookie = {'name': 'foo', 'value': 'bar'}
driver.add_cookie(cookie)
# 现在获取所有当前URL下可获得的Cookies
driver.get_cookies()