Selenium 文档标注

来源:互联网 发布:凡科建站怎么样 知乎 编辑:程序博客网 时间:2024/05/16 16:00

Selenium

3. Navigating

driver.get("http://www.google.com")

driver会等待直到页面加载完成,也就是onload事件出现,之后才会将控制权转给测试脚本。如果使用了AJAX,那么页面还没完全加载结束,就会转移控制权,这时可以使用wait来处理。

3.1 Interacting with the page

<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']")

如果找到多个element那么只会返回第一个,如果一个都没有找到,会触发NoSuchElementException

element.clear()element.send_keys(" and some", Keys.ARROW_DOWN)

send_keys之前,要先clear,否则keys会附加在行尾。也可以发送ARROW_DOWN这种按键。

3.2 Filling in forms

from selenium.webdriver.support.ui import Selectselect = Select(driver.find_element_by_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_optionsoptions = select.options

。。。。

element.submit()

WebDriver will walk up the DOM until it finds the enclosing form and then calls submit on that.
Driver会沿着DOM向上查找submit,如果没有找到,就触发NoSuchElementException

3.3 Drag and drop

element = driver.find_element_by_name("source")target = driver.find_element_by_name("target")from selenium.webdriver import ActionChainsaction_chains = ActionChains(driver)action_chains.drag_and_drop(element, target).perform()

上面代码无法直接用在【滑动条验证】上,这种笔直的滑动(非人类),验证不会通过

3.4 Moving between windows and frames

TODO:??什么是Frame(框架)和windows??

3.5 Popup dialogs

alert = driver.switch_to_alert()

返回当前打开的alert object, 可以获取alert内容

3.6 Navigation: history and location

driver.forward()driver.back()

前进,后退

3.7 Cookies

# Go to the correct domaindriver.get("http://www.example.com")# Now set the cookie. This one's valid for the entire domaincookie = {‘name’ : ‘foo’, ‘value’ : ‘bar’}driver.add_cookie(cookie)# And now output all the available cookies for the current URLdriver.get_cookies()

这里是获取和上传。
存储和使用,可以使用pickle,或者cookielib
pickle比较简洁

4. Locating Elements

  • find_element(s)_by_id
  • find_element(s)_by_name
  • find_element(s)_by_xpath
  • find_element(s)_by_link_text
  • find_element(s)_by_partial_link_text
  • find_element(s)_by_tag_name
  • find_element(s)_by_class_name
  • find_element(s)_by_css_selector

XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言。
XPath wiki

<html> <body>  <p>Are you sure you want to do this?</p>  <a href="continue.html">Continue</a>  <a href="cancel.html">Cancel</a></body><html>continue_link = driver.find_element_by_link_text('Continue')continue_link = driver.find_element_by_partial_link_text('Conti')

5. Waits

5.1 Explicit Waits

from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Firefox()driver.get("http://somedomain/url_that_delays_loading")try:    element = WebDriverWait(driver, 10).until(        EC.presence_of_element_located((By.ID, "myDynamicElement"))    )finally:    driver.quit()

WebDriverWait每隔500ms检测一次,直到设置的timeout时间。

Expected Conditions

  • title_is
  • title_contains
  • presence_of_element_located
    仅仅存在
  • visibility_of_element_located
    存在而且得显示
  • visibility_of
    显示而且长宽不为0
  • presence_of_all_elements_located
  • text_to_be_present_in_element
  • text_to_be_present_in_element_value
  • frame_to_be_available_and_switch_to_it
  • invisibility_of_element_located
    不可见或者在DOM中不存在
  • element_to_be_clickable
  • staleness_of
    element不再附加在DOM上
  • element_to_be_selected
  • element_located_to_be_selected
  • element_selection_state_to_be
  • element_located_selection_state_to_be
  • alert_is_present

7. WebDriver API

7.1 Exceptions

Exceptions

7.2 Action Chains

on_element=None的方法,默认是在当前鼠标位置执行

  • click
  • click_and_hold
  • context_click
  • drag_and_drop
  • drag_and_drop_by_offset
  • key_down
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
  • key_up
  • move_by_offset
  • move_to_element
  • move_to_element_with_offset
  • perform
  • release
  • reset_actions
    Clears actions that are already stored on the remote end.
  • send_keys
  • send_keys_to_element

7.3 Alerts

  • accept()
    Alert(driver).accept() # 确认弹窗
  • authenticate(username, password)
    driver.switch_to.alert.authenticate(‘cheese’, ‘secretGouda’)
    TODO: 这个可以试试
  • dismiss()
  • send_keys()
  • text
    得到alert的内容

7.4 Special Keys

Special Keys

7.6 Desired Capabilities

from selenium import webdriverselenium_grid_url = "http://198.0.0.1:4444/wd/hub"# Create a desired capabilities object as a starting point.capabilities = DesiredCapabilities.FIREFOX.copy()capabilities['platform'] = "WINDOWS"capabilities['version'] = "10"# Instantiate an instance of Remote WebDriver with the desired capabilities.driver = webdriver.Remote(desired_capabilities=capabilities,                          command_executor=selenium_grid_url)

以前通过如下方法设置过heander:

dcap = dict(DesiredCapabilities.PHANTOMJS)dcap["phantomjs.page.settings.userAgent"]=( "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" )browser = webdriver.PhantomJS(executable_path='D:\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe', service_args=SERVICE_ARGS, desired_capabilities=dcap)

这里dcap通过DesiredCapabilities.CHROME.copy()应该也可以实现

7.7 Utilities

??TODO??

7.11 WebElement

  • ..
  • get_attribute
    先尝试获得其property,如果不存在,就尝试获得其attribute,如果没有返回None
# Check if the "active" CSS class is applied to an element.is_active = "active" in target_element.get_attribute("class")
  • get_property
  • screenshot(filename)
    当前element的截图,需要提供完整路径
  • value_of_css_property(property_name)
  • location
  • location_once_scrolled_into_view
    点击元素之前,需要先能看到它。。
  • parent
  • rect
  • size
  • tag_name
  • text

8. Appendix

How to take screenshot of the current window ?

from selenium import webdriverdriver = webdriver.Firefox()driver.get('http://www.python.org/')driver.save_screenshot('screenshot.png')driver.quit()

How to upload files into file inputs ?

Select the element and call the send_keys() method passing the file path, either the path relative to the test script, or an absolute path. Keep in mind the differences in path names between Windows and Unix systems.

How to scroll down to the bottom of a page ?

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

这个是直接翻到底

需要注意地方

  1. 每个会引起element变化的操作,都需要在操作后判断是否操作成功,因为有的时候clickable了,点击却没有反应,如果等待一会再点击就可成功,这是页面刷新的问题:
    ① button点击:使用try except来确定button消失,或者新的element出现,如果没有,那么重新点击
    ② button点击1:有的情况是点击之后页面刷新,那么就没有新的出现或者旧的消失,这时就用time.sleep来等待一段时候,比如1,然后再wait element刷新。不等待直接wait,有时界面来不及刷新,那么就直接wait通过了,但是页面后续才刷新,获取的数据就可能是错的
  2. click,需要保证element可见:页面scroll到相应的位置且没有遮挡
  3. 如果点击出现了新窗口,看着当前窗口转到了新窗口,但是driver实际并没有,需要先切到新窗口再操作
  4. 使用pyquery的时候,一定要注意namespace,可能找不到element。先移除doc = pq(html).remove_namespaces()
原创粉丝点击