1、定位一组元素
意义在于从定位出的一组中筛选我们需要的
1、find_elements_by_id()
2、find_elements_by_name()
3、find_elements_by_class_name()
4、find_elements_by_tag_name()
5、find_elements_by_link_text()
6、find_elements_by_partial_link_text()
7、find_elements_by_xpath()
8、find_elements_by_css_selector()
driver.find_elements_by_id().pop() 中pop()有如下几种用法:
pop()或pop(-1) 取一组元素最后一个
pop(0) 取一组元素第一个
pop(1) 取一组元素第二个
…
二、多表单切换
frame/iframe表单嵌套页面。对于嵌套的页面中 元素的定位,需要使用switch_to.frame()。之后,从嵌套页面回到上一层页面,需要使用switch_to_parent_frame()。
三、多窗口切换
操作的页面打开了一个新页面,切换到新页面需要使用switch_to_window()方法。其中,简介几个获取窗口句柄的方法。
current_handle_handle() 获取当前窗口的句柄
window_handles() 返回打开的所有窗口的句柄到当前会话
四、alert的处理
为了处理网页的alert,我们需要用到switch_to_alert()。此外,我们可以用以下方法获取信息和操作alert
text 返回alert/confirm/prompt中的文字信息
accept() 接受现有警告框
dismiss() 解散现有警告框
send_keys(keysToSend) 发送文本至警告框
text的使用举例:
print(driver.switch_to_alert().text)
五、上传文件
先记一种,还有一种AutoIt上传以后研究。(虽然说,说以后再说 ,基本就是以后都不会做了…)
如果 上传按钮 是 input标签,直接 send_keys()就可以。
举例
driver.find_element_by_xpath('//*[@id="attachments_form"]/span[2]/input').send_keys("F:\\009.jpg")
六、下载文件
Chrome 文件下载,需要设置其options:
download.default_directory:设置下载路径
profile.default_content_settings.popups:设置为 0 禁止弹出窗口
举例:
from selenium import webdriver
from time import sleep
#不懂ChromeOptions()可以看下一篇博文
options = webdriver.ChromeOptions()
prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': 'd:\\'}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path='D:\\chromedriver.exe', chrome_options=options)
driver.get('http://sahitest.com/demo/saveAs.htm')
driver.find_element_by_xpath('//a[text()="testsaveas.zip"]').click()
sleep(3)
driver.quit()
六、爬页面源码
举例:
driver.get(url)
page=driver.page_source
print(page)