selenium

一、什么是Selenium

selenium 是一套完整的web应用程序测试系统,包含了测试的录制(selenium IDE),编写及运行(Selenium Remote Control)和测试的并行处理(Selenium Grid)。Selenium的核心Selenium Core基于JsUnit,完全由JavaScript编写,因此可以用于任何支持JavaScript的浏览器上。

selenium可以模拟真实浏览器,自动化测试工具,支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题。

二、selenium基本使用

声明浏览器对象

上面我们知道了selenium支持很多的浏览器,但是如果想要声明并调用浏览器则需要:

1
2
3
4
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)

driver_path为你所下载的浏览器driver,且储放的位置。其他的支持的浏览器都可以通过这种方式调用

设置无头浏览器

如果你不希望浏览器打开,那么你可以选择使用Chrome或Firefox的无头版本(PhantomJS已经嗝屁)

下面我们来设置一下chrome无头版本

1
2
3
4
5
6
7
8
9
10
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

# 实例化一个对象
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
# 传入该参数
browser = webdriver.Chrome(executable_path=driver_path,options=chrome_options)

访问页面

1
2
3
4
5
6
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
browser.get('https://www.messilessblog.com')
browser.close()

上述代码运行后,会自动打开Chrome浏览器,并登陆百度打印百度首页的源代码,然后关闭浏览器

查找元素

单个元素查找

1
2
3
4
5
6
7
8
9
10
11
12
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
browser.get('https://www.messiless.club')
input_one = browser.find_element_by_id("q")
input_two = browser.find_element_by_css_selector("#q")
input_three = browser.find_element_by_xpath("//div[@id='q']")
print(input_one)
print(input_two)
print(input_three)
browser.close()

这里我们通过五种不同的方式去获取响应的元素,第一种是通过id的方式,第二个中是CSS选择器,第三种是xpath选择器方式结果都是相同的。

这里列举一下常用的查找元素方法:

1
2
3
4
5
6
7
8
find_element_by_name
find_element_by_id
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

下面这种方式是比较通用的一种方式:这里需要记住By模块所以需要导入
from selenium.webdriver.common.by import By

1
2
3
4
5
6
7
8
9
from selenium import webdriver
from selenium.webdriver.common.by import By

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
browser.get('https://www.messilessblog.com')
first = browser.find_element(By.ID,'q')
print(first)
browser.close()

当然这种方法和上述的方式是通用的,browser.find_element(By.ID,”q”)这里By.ID中的ID可以替换为其他几个

多个元素查找

其实多个元素和单个元素的区别,举个例子:find_elements,单个元素是find_element,其他使用上没什么区别,获得的是一个列表

元素交互操作

操作输入框

1
2
3
4
5
6
7
8
9
10
11
12
13
from selenium import webdriver
import time

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
browser.get("http://www.taobao.com")
input_str = browser.find_element_by_id('q')
input_str.send_keys("ipad")
time.sleep(1)
input_str.clear()
input_str.send_keys("MakBook pro")
button = browser.find_element_by_class_name('btn-search')
button.click()

运行的结果可以看出程序会自动打开Chrome浏览器并打开淘宝输入ipad,然后删除,重新输入MakBook pro,并点击搜索

操作checkbox

因为要选中checkbox标签,在网页中是通过鼠标点击的,因此要选中checkbox标签,那么先选中这个标签,再通过执行click事件来完成

1
2
check_ele = browser.find_element_by_id('q')
check_ele.click()

选择select

select元素不能直接点击,因为点击后还要选中元素,因此selenium为select标签专门提供了一个类,selenium.webdriver.support.ui.Select,将获取到的元素当成参数传到这个类中,创建对象,然后就就可以用这个对象进行选择了

1
2
3
4
5
6
7
8
9
10
11
from selenium.webdriver.support import Select
# 选中这个标签,然后用Select创建对象
selectTag = Select(browser.find_element_by_id('q'))
# 根据索引选择
selectTag.select_by_index(1)
# 根据值选择
selectTag.select_by_value('http://www.messiless.club')
# 根据可视文本选择
selectTag.select_by_visible_text('basketboll')
# 取消所有选中
selectTag.deselect_all()

动作链

将动作附加到动作链中串行执行

1
2
3
4
5
6
7
8
9
10
11
12
13
from selenium import webdriver
from selenium.webdriver import ActionChains

driver_path = r'D:\chromedriver\chromedriver.exe'
driver = webdriver.Chrome(executable_path=driver_path)
driver.get('https://www.baidu.com/')
# 先拿到两个标签
inputTag = driver.find_element_by_id('kw')
submitTag = driver.find_element_by_id('su')
ac = ActionChains(driver)
ac.send_keys_to_element(inputTag, 'python')
ac.click(submitTag)
ac.perform()

更多操作:

click_and_hold(element):点击但不松开鼠标

context_click(element):右键点击

double_click(element):双击

等待

当使用了隐式等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常, 换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0

隐式等待
到了一定的时间发现元素还没有加载,则继续等待我们指定的时间,如果超过了我们指定的时间还没有加载就会抛出异常,如果没有需要等待的时候就已经加载完毕就会立即执行

1
2
3
4
5
6
7
8
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
browser.implicitly_wait(10)
browser.get('https://www.zhihu.com/explore')
input = browser.find_element_by_class_name('zu-top-add-question')
print(input)

显示等待

指定一个等待条件,并且指定一个最长等待时间,会在这个时间内进行判断是否满足等待条件,如果成立就会立即返回,如果不成立,就会一直等待,直到等待你指定的最长等待时间,如果还是不满足,就会抛出异常,如果满足了就会正常返回

1
2
3
4
5
6
7
8
9
10
11
12
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

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
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')))
print(input, button)

上述的例子中的条件:EC.presence_of_element_located()是确认元素是否已经出现了
EC.element_to_be_clickable()是确认元素是否是可点击的

常用的判断条件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

执行JavaScript

这是一个非常有用的方法,这里就可以直接调用js方法来实现一些操作,
下面的例子是通过登录知乎然后通过js翻到页面底部,并弹框提示

1
2
3
4
5
6
from selenium import webdriver
driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
browser.get("http://www.zhihu.com/explore")
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
browser.execute_script('alert("To Bottom")')

获取元素属性
get_attribute(‘class’)

1
2
3
4
5
6
7
8
9
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
url = 'https://www.zhihu.com/explore'
browser.get(url)
logo = browser.find_element_by_id('zh-top-link-logo')
print(logo)
print(logo.get_attribute('class'))

获取文本值
text

1
2
3
4
5
6
7
8
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.text)

获取ID,位置,标签名
id
location
tag_name
size

1
2
3
4
5
6
7
8
9
10
11
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.id)
print(input.location)
print(input.tag_name)
print(input.size)

截图

1
2
3
4
5
6
from selenium import webdriver

driver_path = r'D:\chromedriver\chromedriver.exe'
driver = webdriver.Chrome(executable_path=driver_path)
driver.get('https://www.baidu.com/')
driver.save_screenshot('k1.png')

cookie操作

get_cookies()
delete_all_cookes()
add_cookie()

1
2
3
4
5
6
7
8
9
10
11
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
browser.get('https://www.zhihu.com/explore')
# 打印所以cookie
print(browser.get_cookies())
browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'zhaofan'})
print(browser.get_cookies())
browser.delete_all_cookies()
print(browser.get_cookies())

选项卡管理

通过执行js命令实现新开选项卡window.open()
不同的选项卡是存在列表里browser.window_handles
通过browser.window_handles[0]就可以操作第一个选项卡

switch_to_window()被标记成不建议使用,因为已经计划把他从今后版本中去除,目前需要使用switch_to.window()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import time
from selenium import webdriver

driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path)
browser.get('https://www.baidu.com')
# 打开新的页面,虽然打开了新的页面,但是程序当前指向仍为第一个页面
browser.execute_script("window.open('https://www.messilessblog.com')")
# window_handles是一个列表,装的是页面句柄
print(browser.window_handles)
# 将页面切换成第二个页面
browser.switch_to.window(browser.window_handles[1])
# 打印当前页面的url
print(browser.current_url)
# 打印当前页面的源代码
print(browser.page_source)
browser.get('https://www.taobao.com')
time.sleep(1)
browser.switch_to.window(browser.window_handles[0])
browser.get('https://python.org')

设置代理ip

因为经常爬取网站可能会被封ip,所以我们需要代理ip

1
2
3
4
5
6
7
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--proxy-server=http://1.183.162.5:43235")
driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
browser = webdriver.Chrome(executable_path=driver_path,options=options)
# 这个网站可以查看当前ip
browser.get('http://httpbin.org/ip')