- 目录
1.简介
Selenium是一个用于Web应用程序测试的工具。直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Firefox,Safari,Chrome,Opera等,在爬虫上则是模拟正常用户访问网页并获取数据。
2.安装 Selenium
> pip install selenium
3.安装驱动
模拟真正的用户操作当然需要选择好用来操作的浏览器,根据浏览器来安装相应的驱动调起。
3.1 Chrome
使用selenium驱动chrome浏览器需要下载chromedriver,而且chromedriver版本需要与chrome的版本对应,版本错误的话则会运行报错。
查看chrome的版本,可通过帮助 > 关于Google Chrome(G)
。
下载chromedriver可以通过淘宝镜像地址:http://npm.taobao.org/mirrors/chromedriver/ 。最新的镜像与Chrome同名,尽量选择版本相近的避免兼容问题,镜像下notes.txt可查看当前驱动支持的版本。
选择合适的版本下载,下载完解压将chromedriver.exe放在有设置环境变量的目录下,小编是放在python的安装目录下的,即python.exe所在的目录。
3.2 Firefox
使用selenium驱动Firefox浏览器需要下载geckodriver,查看浏览器版本通过帮助 > 关于 Firefox
。
下载geckodriver可通过mozilla的仓库地址:https://github.com/mozilla/geckodriver/releases。
选择合适的版本下载,解压后geckodriver.exe同样也是放在python的安装目录下。
3.3 其它浏览器驱动下载
Opera:http://npm.taobao.org/mirrors/operadriver/
IE:http://selenium-release.storage.googleapis.com/index.html (版本号要与selenium的版本一致,查看安装的selenium版本,可通过pip show selenium
)如果没有vpn可能会打不开,可点击下载3.14.0版本的。
4.Selenium使用
4.1 Chrome 配置
options = webdriver.ChromeOptions()
## 无界面
# options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=options)
driver.set_window_size(1366, 768)
driver.set_page_load_timeout(self.timeout)
注意Chrome可能需要管理员权限相关配置,小编习惯性用Firefox😂
4.2 Firefox 配置
# 实例化参数对象
options = webdriver.FirefoxOptions()
# 无界面
# options.add_argument('--headless')
driver = webdriver.Firefox(firefox_options=options)
driver.set_window_size(1400, 700)
driver.set_page_load_timeout(self.timeout)
4.3 不显示打开浏览器的界面
有的时候我们不想要看到爬取的一步步操作,只关心结果,则可以在参数配置
# 无界面
options.add_argument('--headless')
4.4 禁用浏览器弹窗
不是页面弹窗,是浏览器设置里的弹窗。在打开浏览器时,使用参数配置关闭
Firefox
options.set_preference('dom.webnotifications.enabled', False)
options.set_preference('dom.push.enabled', False)
Chrome
prefs = {
'profile.default_content_setting_values': {
'notifications': 2
}
}
options.add_experimental_option('prefs', prefs)
4.5 driver属性和方法
-
页面加载
driver.get("http://www.baidu.com")
-
关闭浏览器
# 爬虫结束关闭浏览器 driver.close()
-
获取当前url
driver.current_url
-
刷新
driver.refresh()
-
页面标题
driver.title
-
页面渲染后的源码
driver.page_source
-
获取窗口信息
driver.get_window_rect()
获取当前窗口的x,y坐标和当前窗口的高度和宽度,如:{'height': 1366, 'width': 768, 'x': 0, 'y': 200}
-
设置 User Agent(Firefox为例)
profile = webdriver.FirefoxProfile() profile.set_preference("general.useragent.override", "some UA string") driver = webdriver.Firefox(profile=profile)
-
执行js脚本
使用
driver.execute_script([js脚本],*args)
同步执行,如滑动到第一个class为cm-explain-bottom的元素位置。driver.execute_script( "document.getElementsByClassName('cm-explain-bottom')[0].scrollIntoView(true)")
异步执行使用
driver.execute_async_script([js脚本],*args)
,*argsw为执行js代码要传入的参数。 -
查找元素
返回一个
WebElement
对象。- 通过id属性:
element = driver.find_element_by_id("coolestWidgetEvah")
- 通过class属性:
cheeses = driver.find_elements_by_class_name("cheese")
- 通过标签名:
frame = driver.find_element_by_tag_name("iframe")
- 通过css选择器:
cheese = driver.find_element_by_css_selector("#food span.dairy.aged")
- 通过name属性:
cheese = driver.find_element_by_name("cheese")
- 通过xpath:
inputs = driver.find_elements_by_xpath("//input")
- 通过链接文本(完全匹配):
cheese = driver.find_element_by_link_text("cheese")
- 通过链接文本(部分匹配):
cheese = driver.find_element_by_partial_link_text("cheese")
- 通过id属性:
-
元素(WebElement)的属性和方法
标签下文本:
element.text
点击:
element.click()
表单提交:
element.submit()
输入:
element.send_keys(123)
示例:
# 等待邮箱和密码可定位及登录按钮可提交,清空输入框,分别输入用户名密码点击提交按钮 email = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#email"))) passwd = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#pass"))) submit = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#loginbutton'))) email.clear() passwd.clear() email.send_keys(user) passwd.send_keys(password) submit.click()
-
Cookie操作
driver.get("http://www.example.com") # 给当前url域设置cookie # name的值对应cookie key,value的值对应cookie value driver.add_cookie({'name':'key', 'value':'value', 'path':'/'}) # 可选的属性 # 'domain' -> String, # 'secure' -> Boolean, # 'expiry' -> Milliseconds since the Epoch it should expire. # 输出当前url所有的Cookie for cookie in driver.get_cookies(): print "%s -> %s" % (cookie['name'], cookie['value']) # 通过name删除Cookie driver.delete_cookie("CookieName") # 删除所有的Cookie driver.delete_all_cookies()
-
切换页面框架或窗口
driver.switch_to.window("windowName")
切换默认框架:
driver.switch_to.default_content()
切换最新窗口:
windows = driver.window_handles # 切换到最新打开的窗口中 switch_to.window(windows[-1])
-
获取最新的alert弹窗
alert = driver.switch_to.alert # 关闭弹窗 alert.dismiss()
-
当前的url返回或者跟进
driver.forward() driver.back()
-
截屏
# 返回页面的base64编码字符串 base64 = driver.get_screenshot_as_base64() # 返回保存到文件的结果 result = driver.get_screenshot_as_file("D:\\example.png") # png格式的二进制字符串 pngSrc = driver.get_screenshot_as_png()
使用Selenium爬取七麦数据APP排行榜:点击前往