1、selenium是什么?
Selenium 是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl等不同语言的测试脚本。(转自百度百科)
2、python中的selenium使用
代码链接:https://github.com/princewen/python3_crawl
先来看一段完整的的代码:
"""基本使用"""
fromseleniumimportwebdriver
fromselenium.webdriver.common.byimportBy
fromselenium.webdriver.common.keysimportKeys
fromselenium.webdriver.supportimportexpected_conditionsasEC
fromselenium.webdriver.support.waitimportWebDriverWait
browser=webdriver.Chrome()
try:
browser.get('https://www.baidu.com')
#找到百度的输入框
input=browser.find_element_by_id('kw')
#在输入框中输入python
input.send_keys('Python')
#回车进行搜索
input.send_keys(Keys.ENTER)
#等待10s
wait=WebDriverWait(browser,10)
#直到contnet_left元素出现
wait.until(EC.presence_of_element_located((By.ID,'content_left')))
#打印当前url
print(browser.current_url)
#打印当前的cookie
print(browser.get_cookies())
#打印当前的源代码
print(browser.page_source)
finally:
browser.close()
在上面的代码中,我们先使用Chrome内核构造了一个浏览器,获取到了百度的链接,随后找到了百度输入框元素,在输入框中输入python并回车,相当于使用百度搜索python,使用显式等待页面内容出现,最后我们打印了url、cookie和页面源代码。
接下来我们将详细介绍selenium的功能。
2.1 访问页面
使用get方法请求一个页面
browser=webdriver.Chrome()browser.get('https://www.taobao.com')print(browser.page_source)browser.close()
2.2 查找元素
查找元素分为查找一个元素或者查找多个元素,可以使用通用的方法或者非通用方法,在通用方法中需要通过By的方式指定查找方式。查找方式可以通过id、class、name、xpath等形式。
#单个元素#除了下面的方式外,还有其它方式browser=webdriver.Chrome()browser.get('https://www.taobao.com')input_first=browser.find_element_by_id('q')input_second=browser.find_element_by_css_selector('#q')input_third=browser.find_element_by_xpath('//*[@id="q"]')print(input_first,input_second,input_third)browser.close()#通用方式browser=webdriver.Chrome()browser.get('https://www.taobao.com')input_first=browser.find_element(By.Id,'q')print(input_first)browser.close()#查找多个元素browser=webdriver.Chrome()browser.get('https://www.taobao.com')lis=browser.find_elements_by_css_selector(('.service-bd li'))lis_2=browser.find_elements(By.CSS_SELECTOR,'.service-bd li')#返回一个列表print(lis)print(lis_2)browser.close()
2.3 元素交互操作
元素的交互操作,比如在文标框中输入文字、清除文本框中的文字,点击按钮等等。
importtimebrowser=webdriver.Chrome()browser.get('https://www.taobao.com')input=browser.find_element_by_id('q')input.send_keys('iPhone')time.sleep(1)input.clear()input.send_keys('iPad')button=browser.find_element_by_class_name('btn-search')button.click()
2.4 交互动作
交互动作使用ActionChains,这里的代码展示了把元素从一个位置拖动到另一个位置的代码。
fromselenium.webdriverimportActionChainsbrowser=webdriver.Chrome()url='http://www.runoob.com/try/try.php?filename=jqueryul-api=dropable'browser.get(url)#切换到iframebrowser.switch_to.frame('iframeResult')source=browser.find_element_by_css_selector('#draggable')target=browser.find_element_by_css_selector('#droppable')actions=ActionChains(browser)actions.drag_and_drop(source,target)actions.perform()
2.5 执行javascript
browser=webdriver.Chrome()browser.get('https://www.zhihu.com/explore')browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')browser.execute_script('alert("To Bottom")')browser.close()
2.6 获取元素属性
可以通过get_attribute方法得到元素属性,对于某些关键字,直接使用.就可以获得。
"""获取元素属性"""browser=webdriver.Chrome()browser.get('https://www.zhihu.com/explore')logo=browser.find_element_by_id('zh-top-link-logo')print(logo)# 获取classprint(logo.get_attribute('class'))input=browser.find_element_by_class_name('zu-top-add-question')#获取文本print(input.text)#获取其他信息print(input.id)print(input.location)print(input.tag_name)print(input.size)
2.7 切换frame
页面之间frame的切换,需要注意的是在子frame中无法获得父frame的元素。
fromselenium.common.exceptionsimportNoSuchElementExceptionbrowser=webdriver.Chrome()url='http://www.runoob.com/try/try.php?filename=jqueryul-api=dropable'browser.get(url)#切换到iframebrowser.switch_to.frame('iframeResult')source=browser.find_element_by_css_selector('#draggable')try:logo=browser.find_element_by_class_name('logo')except NoSuchElementException:print('NO LOGO')browser.switch_to.parent_frame()logo=browser.find_element_by_class_name('logo')print(logo)print(logo.text)
2.8 等待
等待分为隐式等待和显式等待。在隐式等待中,只需要指定一个等待时间,当我们获取元素时,如果超过等待时间还没有获取到元素,会抛出异常。显示等待构造WebDriverWait对象,调用其until方法指定一个元素并制定相应的等待形式,如元素的加载,元素可点击等等,如果超过等待时间指定的元素没有呈现或者不可点击,那么就会抛出异常。
browser=webdriver.Chrome()browser.get('https://www.zhihu.com/explore')"""隐式等待"""browser.implicitly_wait(10)"""如果这个元素没有找到的话,会等待10s,如果还没有找到,就会抛出异常"""logo=browser.find_element_by_id('zh-top-link-logo')print(logo)# 获取classprint(logo.get_attribute('class'))browser.close()"""显示等待"""
fromselenium.webdriver.supportimportexpected_conditionsasECfromselenium.webdriver.support.waitimportWebDriverWait
browser=webdriver.Chrome()browser.get('https://www.taobao.com/')wait=WebDriverWait(browser,10)#参数是元组,还有其他一些等待条件input=wait.until(EC.presence_of_element_located((By.ID,'q')))button=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.btn-search')))browser.close()
2.9 前进后退
browser=webdriver.Chrome()browser.get('https://www.baidu.com')browser.get('https://www.taobao.com')browser.get('https://www.python.org')browser.back()time.sleep(1)browser.forward()browser.close()
2.10 cookies操作
browser=webdriver.Chrome()browser.get('https://www.zhihu.com/explore')print(browser.get_cookies())browser.add_cookie({'name':'name','domain':'www.zhihu.com','value':'germey'})print(browser.get_cookies())browser.delete_all_cookies()print(browser.get_cookies())
2.11 选项卡管理
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.zhihu.com/explore')browser.switch_to_window(browser.window_handles[0])browser.get('https://python.org')browser.close()
2.12 异常处理
fromselenium.common.exceptionsimportNoSuchElementException,TimeoutExceptionbrowser=webdriver.Chrome()try:browser.get('https://www.baidu.com')except TimeoutException:print('TIme out')try:browser.find_element_by_id('hello')except NoSuchElementException:print('NOT FOUND')