1. 一个简单的使用例子
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait browser = webdriver.Chrome() try: browser.get('https://www.baidu.com') input = browser.find_element_by_id('kw') input.send_keys('Python') input.send_keys(Keys.ENTER) wait = WebDriverWait(browser, 10) wait.until(EC.presence_of_element_located((By.ID, 'content_left'))) print(browser.current_url) print(browser.get_cookies()) //列表的形式打印出来 print(browser.page_source) finally: browser.close()
2. 声明浏览器对象的几种方法,都需要单独下载相应的软件包
from selenium import webdriver
browser = webdriver.Chrome() browser = webdriver.Firefox() browser = webdriver.Edge() browser = webdriver.PhantomJS() browser = webdriver.Safari()
我用的chrome, 下载地址 http://chromedriver.storage.googleapis.com/index.html, 解压复制到python目录下
备用各版本下载地址 http://npm.taobao.org/mirrors/chromedriver/
3. 访问页面
from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.taobao.com') print(browser.page_source)
#在window下需要转下码 print(browser.page_source.encode('utf-8')) browser.close()
4. 查找元素
4.1:单个元素,下面三种方法输出结果是一样的
from selenium import webdriver 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()
常用的几种方法
- find_element_by_name
- find_element_by_xpath
- find_element_by_link_text
- find_element_by_partial_link_text
- find_element_by_tag_name
- find_element_by_class_name
- find_element_by_css_selector
为了方便,一般用如下的通用方法,只修改方法中的参数即可
from selenium import webdriver from selenium.webdriver.common.by import By browser = webdriver.Chrome() browser.get('https://www.taobao.com') input_first = browser.find_element(By.ID, 'q') //通用的方法 print(input_first) browser.close()
4.2:多个元素
from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.taobao.com') lis = browser.find_elements_by_css_selector('.service-bd li') print(lis) browser.close()
同样也有几种常用的方法如下
- find_elements_by_name
- find_elements_by_xpath
- find_elements_by_link_text
- find_elements_by_partial_link_text
- find_elements_by_tag_name
- find_elements_by_class_name
- find_elements_by_css_selector
也有通用的方法
from selenium import webdriver from selenium.webdriver.common.by import By browser = webdriver.Chrome() browser.get('https://www.taobao.com') lis = browser.find_elements(By.CSS_SELECTOR, '.service-bd li') print(lis) browser.close()
5. 元素交互操作
对获取的元素调用交互方法
from selenium import webdriver import time browser = webdriver.Chrome() browser.get('https://www.taobao.com') input = browser.find_element_by_id('q') //输入框的id为q,这里就是查找到输入框 input.send_keys('iPhone') //在输入框中输入iPhone time.sleep(1) input.clear() input.send_keys('iPad') //休息一秒后清除输入框中的iphone,再输入ipad button = browser.find_element_by_class_name('btn-search') //查找到搜索按钮 button.click() //点击搜索按钮
更多操作: http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement
6. 交互动作
将动作附加到动作链中串行执行,也就是执行拖拽动作
from selenium import webdriver from selenium.webdriver import ActionChains browser = webdriver.Chrome() url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable' browser.get(url) browser.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()
更多操作: http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains
7. 执行javascript
from selenium import webdriver 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")') //弹出一个警告框
8. 获取元素信息
8.1:获取属性
from selenium import webdriver from selenium.webdriver import ActionChains browser = webdriver.Chrome() url = 'https://www.zhihu.com/explore' browser.get(url) logo = browser.find_element_by_id('zh-top-link-logo') //根据ID找到"知乎"logo print(logo) print(logo.get_attribute('class')) //得到这个logo的class属性
8.2:获取文本值
from selenium import webdriver browser = webdriver.Chrome() url = 'https://www.zhihu.com/explore' browser.get(url) input = browser.find_element_by_class_name('zu-top-add-question') //根据类名找到页面头部的"提问"元素 print(input.text) //打印出元素文本,即"提问"
8.3:获取ID,位置,标签名,大小
from selenium import webdriver browser = webdriver.Chrome() url = 'https://www.zhihu.com/explore' browser.get(url) input = browser.find_element_by_class_name('zu-top-add-question') print(input.id) //输出为0.8858844079340578-1 print(input.location) //打印出坐标值,测试是{'y': 7, 'x': 225} print(input.tag_name) //打印出标签名,这里是button print(input.size) //打印button按钮的尺寸,输出为{'height': 32, 'width': 66}
9. Frame
import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException browser = webdriver.Chrome() url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable' browser.get(url) browser.switch_to.frame('iframeResult') //切换到id名为iframeResult的iframe标签内 source = browser.find_element_by_css_selector('#draggable') print(source) try: logo = browser.find_element_by_class_name('logo') except NoSuchElementException: print('NO LOGO') browser.switch_to.parent_frame() //切换到id名为iframeResult的iframe标签外,这样才能得到iframe标签外的元素。 logo = browser.find_element_by_class_name('logo') print(logo) print(logo.text)
10. 等待
10.1:隐式等待,当使用了隐式等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常, 换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0
from selenium import webdriver browser = webdriver.Chrome() browser.implicitly_wait(10) browser.get('https://www.zhihu.com/explore') input = browser.find_element_by_class_name('zu-top-add-question') print(input)
10.2:显示等待,指定时间内是否能满足设定的条件,如果满足则正常返回,否则返回异常
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC browser = webdriver.Chrome() browser.get('https://www.taobao.com/') wait = WebDriverWait(browser, 10) //设置指定时间为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'))) print(input, button)
一些常见的设定条件如下
- title_is 标题是某内容
- title_contains 标题包含某内容
- presence_of_element_located 元素加载出,传入定位元组,如(By.ID, 'p')
- visibility_of_element_located 元素可见,传入定位元组
- visibility_of 可见,传入元素对象
- 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 frame加载并切换
- invisibility_of_element_located 元素不可见
- element_to_be_clickable 元素可点击
- staleness_of 判断一个元素是否仍在DOM,可判断页面是否已经刷新
- element_to_be_selected 元素可选择,传元素对象
- element_located_to_be_selected 元素可选择,传入定位元组
- element_selection_state_to_be 传入元素对象以及状态,相等返回True,否则返回False
- element_located_selection_state_to_be 传入定位元组以及状态,相等返回True,否则返回False
- alert_is_present 是否出现Alert
详细内容:http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions
11. 前进后退
import time from selenium import webdriver 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() //前进到python页面 browser.close()
12. cookies
from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.zhihu.com/explore') print(browser.get_cookies()) //网页上查看cookie方法:F12找到Application选项卡,里面有cookie项 browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'germey'}) print(browser.get_cookies()) browser.delete_all_cookies() print(browser.get_cookies())
13. 选项卡管理,就是在同一个浏览器中打开多个页面
import time from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.baidu.com') browser.execute_script('window.open()') //通过js打开一个新选项卡 print(browser.window_handles) //返回所有选项卡的引用 browser.switch_to_window(browser.window_handles[1]) //切换到第2个选项卡 browser.get('https://www.taobao.com') time.sleep(1) browser.switch_to_window(browser.window_handles[0]) //切换到第一个选项卡 browser.get('https://python.org')
14. 异常处理
当网页中没有查找的元素时,会报异常
from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.baidu.com') browser.find_element_by_id('hello')
捕获异常,并给出相应处理
from selenium import webdriver from selenium.common.exceptions import TimeoutException, NoSuchElementException browser = webdriver.Chrome() try: browser.get('https://www.baidu.com') except TimeoutException: print('Time Out') try: browser.find_element_by_id('hello') except NoSuchElementException: print('No Element') finally: browser.close()
详细文档:http://selenium-python.readthedocs.io/api.html#module-selenium.common.exceptions