• 一 介绍
  • 二 安装
  • 三 基本使用
  • 四 选择器
  • 五 等待元素被夹在
  • 元素交互操作
  • 其他
  • 项目联

一 介绍

selenium最初是一个自动化测试的工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题

selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,支持多种浏览器

from selenium import webdriver
browser=webdriver.Chrome()
browser=webdriver.Firefox()
browser=webdriver.PhantomJS()
browser=webdriver.Safari()
browser=webdriver.Edge()

二 安装

1、有界面浏览器

#安装:selenium+chromedriver
pip3 install selenium
chromedriver下载地址:http://chromedriver.storage.googleapis.com/index.html
浏览器版本和驱动版本的对应关系表: https://blog.csdn.net/huilan_same/article/details/51896672

2、无界面浏览器

PhantomJS不再更新

#安装:selenium+phantomjs
pip3 install selenium
下载phantomjs,解压后把phantomjs.exe所在的bin目录放到环境变量
下载链接:http://phantomjs.org/download.html #验证安装
C:\Users\Administrator>phantomjs
phantomjs> console.log('egon gaga')
egon gaga
undefined
phantomjs> ^C
C:\Users\Administrator>python3
Python 3.6. (v3.6.1:69c0db5, Mar , ::) [MSC v. bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from selenium import webdriver
>>> driver=webdriver.PhantomJS() #无界面浏览器
>>> driver.get('https://www.baidu.com')
>>> driver.page_source

在 PhantomJS 年久失修, 后继无人的节骨眼 
Chrome 出来救场, 再次成为了反爬虫 Team 的噩梦

自Google 发布 chrome 59 / 60 正式版 开始便支持Headless mode

这意味着在无 GUI 环境下, PhantomJS 不再是唯一选择

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('window-size=1920x3000') #指定浏览器分辨率
chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('--hide-scrollbars') #隐藏滚动条, 应对一些特殊页面
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
chrome_options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" #手动指定使用的浏览器位置 driver=webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://www.baidu.com') print('hao123' in driver.page_source) driver.close() #切记关闭浏览器,回收资源

selenium+谷歌浏览器headless模式

三、基本使用

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
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_tag=browser.find_element_by_id('kw')
input_tag.send_keys('美女') #python2中输入中文错误,字符串前加个u
input_tag.send_keys(Keys.ENTER) #输入回车 wait=WebDriverWait(browser,)
wait.until(EC.presence_of_element_located((By.ID,'content_left'))) #等到id为content_left的元素加载完毕,最多等10秒 print(browser.page_source)
print(browser.current_url)
print(browser.get_cookies()) finally:
browser.close()

四、选择器

一、基本用法

#官网链接:http://selenium-python.readthedocs.io/locating-elements.html
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #键盘按键操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
import time driver=webdriver.Chrome()
driver.get('https://www.baidu.com')
wait=WebDriverWait(driver,) try:
#===============所有方法===================
# 、find_element_by_id
# 、find_element_by_link_text
# 、find_element_by_partial_link_text
# 、find_element_by_tag_name
# 、find_element_by_class_name
# 、find_element_by_name
# 、find_element_by_css_selector
# 、find_element_by_xpath
# 强调:
# 、上述均可以改写成find_element(By.ID,'kw')的形式
# 、find_elements_by_xxx的形式是查找到多个元素,结果为列表 #===============示范用法===================
# 、find_element_by_id
print(driver.find_element_by_id('kw')) # 、find_element_by_link_text
# login=driver.find_element_by_link_text('登录')
# login.click() # 、find_element_by_partial_link_text
login=driver.find_elements_by_partial_link_text('录')[]
login.click() # 、find_element_by_tag_name
print(driver.find_element_by_tag_name('a')) # 、find_element_by_class_name
button=wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'tang-pass-footerBarULogin')))
button.click() # 、find_element_by_name
input_user=wait.until(EC.presence_of_element_located((By.NAME,'userName')))
input_pwd=wait.until(EC.presence_of_element_located((By.NAME,'password')))
commit=wait.until(EC.element_to_be_clickable((By.ID,'TANGRAM__PSP_10__submit'))) input_user.send_keys('')
input_pwd.send_keys('xxxxxx')
commit.click() # 、find_element_by_css_selector
driver.find_element_by_css_selector('#kw') # 、find_element_by_xpath time.sleep() finally:
driver.close()

二、xpath

#官网链接:http://selenium-python.readthedocs.io/locating-elements.html
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #键盘按键操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
import time driver=webdriver.PhantomJS()
driver.get('https://doc.scrapy.org/en/latest/_static/selectors-sample1.html')
# wait=WebDriverWait(driver,)
driver.implicitly_wait() #使用隐式等待 try:
# find_element_by_xpath
#//与/
# driver.find_element_by_xpath('//body/a') # 开头的//代表从整篇文档中寻找,body之后的/代表body的儿子,这一行找不到就会报错了 driver.find_element_by_xpath('//body//a') # 开头的//代表从整篇文档中寻找,body之后的//代表body的子子孙孙
driver.find_element_by_css_selector('body a') #取第n个
res1=driver.find_elements_by_xpath('//body//a[1]') #取第一个a标签
print(res1[].text) #按照属性查找,下述三者查找效果一样
res1=driver.find_element_by_xpath('//a[5]')
res2=driver.find_element_by_xpath('//a[@href="image5.html"]')
res3=driver.find_element_by_xpath('//a[contains(@href,"image5")]') #模糊查找
print('==>', res1.text)
print('==>',res2.text)
print('==>',res3.text) #其他
res1=driver.find_element_by_xpath('/html/body/div/a')
print(res1.text) res2=driver.find_element_by_xpath('//a[img/@src="data:image3_thumb.jpg"]') #找到子标签img的src属性为image3_thumb.jpg的a标签
print(res2.tag_name,res2.text) res3 = driver.find_element_by_xpath("//input[@name='continue'][@type='button']") #查看属性name为continue且属性type为button的input标签
res4 = driver.find_element_by_xpath("//*[@name='continue'][@type='button']") #查看属性name为continue且属性type为button的所有标签 time.sleep() finally:
driver.close()

三、获取标签属性

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
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() browser.get('https://www.amazon.cn/') wait=WebDriverWait(browser,)
wait.until(EC.presence_of_element_located((By.ID,'cc-lm-tcgShowImgContainer'))) tag=browser.find_element(By.CSS_SELECTOR,'#cc-lm-tcgShowImgContainer img') #获取标签属性,
print(tag.get_attribute('src')) #获取标签ID,位置,名称,大小(了解)
print(tag.id)
print(tag.location)
print(tag.tag_name)
print(tag.size) browser.close()

五、等待元素被加载

#、selenium只是模拟浏览器行为,而浏览器解析页面是需要时间的(执行css,js),一些元素可能需要过一段时间才能加载出来,为了保证能查找到元素,必须等待。

#、等待的方式分两种:
隐式等待:在browser.get('xxx')前设置,针对所有元素有效
显式等待:在browser.get('xxx')后设置,只针对某个元素有效
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
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() #隐式等待:在查找所有元素时,如果尚未被加载,则等10秒
browser.implicitly_wait() browser.get('https://www.baidu.com') input_tag=browser.find_element_by_id('kw')
input_tag.send_keys('美女')
input_tag.send_keys(Keys.ENTER) contents=browser.find_element_by_id('content_left') #没有等待环节而直接查找,找不到则会报错
print(contents) browser.close()

隐式等待

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
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()
browser.get('https://www.baidu.com') input_tag=browser.find_element_by_id('kw')
input_tag.send_keys('美女')
input_tag.send_keys(Keys.ENTER) #显式等待:显式地等待某个元素被加载
wait=WebDriverWait(browser,)
wait.until(EC.presence_of_element_located((By.ID,'content_left'))) contents=browser.find_element(By.CSS_SELECTOR,'#content_left')
print(contents) browser.close()

显式等待

六 元素交互操作

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys tiga=webdriver.Chrome()
tiga.get('https://www.jd.com/')
tiga.implicitly_wait() try:
key=tiga.find_element_by_id('key')
key.send_keys('iphone')
key.send_keys(Keys.ENTER) time.sleep() d=tiga.find_element_by_id('key')
d.clear()
d.send_keys('电脑')
d.send_keys(Keys.ENTER) time.sleep() except Exception:
pass
finally:
tiga.close()

点击、清空

import time
from selenium import webdriver
from selenium.webdriver import ActionChains tiga=webdriver.Chrome()
tiga.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
tiga.implicitly_wait() try:
tiga.switch_to.frame('iframeResult')
source=tiga.find_element_by_id('draggable')
target=tiga.find_element_by_id('droppable') #方法一
# chain=ActionChains(tiga)
# chain.drag_and_drop(source,target)
# chain.perform() #方法二
ActionChains(tiga).click_and_hold(source).perform()
distance = target.location['x'] - source.location['x'] track =
while track < distance:
ActionChains(tiga).move_by_offset(xoffset=, yoffset=).perform()
track += ActionChains(tiga).release().perform() time.sleep() except Exception:
pass
finally:
tiga.close()

Action Chains

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #键盘按键操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 try:
browser=webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.execute_script('alert("hello world")') #打印警告
finally:
browser.close()

在交互动作比较难实现的时候可以自己写JS(万能方法)

# frame相当于一个单独的网页,在父frame里无法直接查看到自frame的元素,必须switch_to_frame下,才能进一步查找

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #键盘按键操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素 try:
browser=webdriver.Chrome()
browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') browser.switch_to.frame('iframeResult') #切换到id为iframeResult的frame tag1=browser.find_element_by_id('droppable')
print(tag1) # tag2=browser.find_element_by_id('textareaCode') #报错,在子frame里无法查看到父frame的元素
browser.switch_to.parent_frame() #切回父frame,就可以查找到了
tag2=browser.find_element_by_id('textareaCode')
print(tag2) finally:
browser.close()

frame的切换

七 其他

#模拟浏览器的前进后退
import time
from selenium import webdriver browser=webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.get('https://www.taobao.com')
browser.get('http://www.sina.com.cn/') browser.back()
time.sleep()
browser.forward()
browser.close()

模拟浏览器的前进后退

#cookies
from selenium import webdriver browser=webdriver.Chrome()
browser.get('https://www.zhihu.com/explore')
print(browser.get_cookies())
browser.add_cookie({'k1':'xxx','k2':'yyy'})
print(browser.get_cookies()) # browser.delete_all_cookies()

cookies

#选项卡管理:切换选项卡,有js的方式windows.open,有windows快捷键:ctrl+t等,最通用的就是js的方式
import time
from selenium import webdriver 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[])
browser.get('https://www.taobao.com')
time.sleep()
browser.switch_to_window(browser.window_handles[])
browser.get('https://www.sina.com.cn')
browser.close()

选项卡管理

from selenium import webdriver
from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException try:
browser=webdriver.Chrome()
browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
browser.switch_to.frame('iframssseResult') except TimeoutException as e:
print(e)
except NoSuchFrameException as e:
print(e)
finally:
browser.close()

异常处理

八 练习

from selenium import webdriver
from time import sleep #创建一个浏览器对象executable_path驱动的路径
bro = webdriver.Chrome(executable_path='./chromedriver.exe')
#get方法可以指定一个url,让浏览器进行请求
bro.implicitly_wait()
bro.get('https://mail.163.com/') try:
# 切换到登陆的iframe
sle = bro.find_element_by_xpath('//*[@id="loginDiv"]/iframe').get_attribute("id")
bro.switch_to.frame(sle) # 输入账号密码登陆
user = bro.find_element_by_name('email')
pwd = bro.find_element_by_name('password')
user.send_keys('xuchaoqiang')
pwd.send_keys('...')
button = bro.find_element_by_id('dologin')
button.click()#click表示的是点击操作 # 点击写信按钮发邮件
write_btn = bro.find_element_by_id("_mail_component_24_24")
write_btn.click() # 输入收信人
recipient = bro.find_element_by_class_name("nui-editableAddr-ipt")
recipient.send_keys("825645848@qq.com")
# 输入写信内容(切换frame)//*[@id="_mail_editor_0_212"]/div[1]/div[2]/iframe
fx = bro.find_element_by_xpath('//iframe[@class="APP-editor-iframe"]')
bro.switch_to.frame(fx)
send_text = bro.find_element_by_class_name("nui-scroll")
send_text.send_keys('test1') #切换到父frame
bro.switch_to.parent_frame() # 点击发送邮件
send_btn = bro.find_element_by_xpath('//div[@class="nui-toolbar-item"]/div[1]')
send_btn.click() except Exception:
pass
finally:
bro.quit()#关闭浏览器

自动登录163邮箱并发送邮件

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time def get_goods(driver):
try:
goods_list = driver.find_elements_by_class_name("gl-item")
for good in goods_list:
p_url = good.find_element_by_tag_name("a").get_attribute("href")
p_name = good.find_element_by_css_selector(".p-name em").text.replace("\n", " ")
p_price = good.find_element_by_css_selector(".p-price i").text
p_comment = good.find_element_by_css_selector(".p-commit").text msg = '''
商品 : %s
链接 : %s
价钱 :%s
评论 :%s
''' % (p_name,p_url,p_price,p_comment) print(msg, end='\n')
button=driver.find_element_by_partial_link_text('下一页')
button.click()
time.sleep()
get_goods(driver)
except Exception:
pass def spider(url, keyword):
driver = webdriver.Chrome(executable_path='./chromedriver.exe')
driver.get(url)
driver.implicitly_wait() try:
key = driver.find_element_by_id("key")
key.send_keys(keyword)
key.send_keys(Keys.ENTER)
get_goods(driver)
finally:
bro.close() if __name__ == '__main__':
spider("https://www.jd.com/", keyword='iPhone8手机')

爬取京东商品信息

补充

driver对象用xpath筛选出元素的selenium对象,使用get_attribute("##")来获取属性值

selenium模块的更多相关文章

  1. 爬虫基础(三)-----selenium模块应用程序

    摆脱穷人思维 <三> :  培养"目标导向"的思维:  好项目永远比钱少,只要目标正确,钱总有办法解决. 一 selenium模块 什么是selenium?seleni ...

  2. 爬虫之selenium模块

    Selenium 简介 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 selenium本质是通过驱动浏览器,完全模拟 ...

  3. 使用Selenium模块报错的解决办法 (FileNotFound,WebDriverException)

    添加Chrome浏览器程序的目录到系统Path变量中: C:\Users\%USERNAME%\AppData\Local\Google\Chrome\Application ,使用pip3 inst ...

  4. Python爬虫——selenium模块

    selenium模块介绍 selenium最初是一个测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 selenium本质是通过驱动浏览器,完全模拟浏览 ...

  5. python 全栈开发,Day136(爬虫系列之第3章-Selenium模块)

    一.Selenium 简介 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 selenium本质是通过驱动浏览器,完全 ...

  6. 三: 爬虫之selenium模块

    一 selenium模块 什么是selenium?selenium是Python的一个第三方库,对外提供的接口可以操作浏览器,然后让浏览器完成自动化的操作. selenium最初是一个自动化测试工具, ...

  7. 7 selenium 模块

    selenium 模块 一.简介 1.Python的一个第三方库,对外提供的接口可以操作浏览器,然后让浏览器完成自动化的操作. 2.自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接 ...

  8. 03 爬虫之selenium模块

    selenium模块 1.概念,了解selenium 什么是selenium?selenium是Python的一个第三方库,对外提供的接口可以操作浏览器,然后让浏览器完成自动化的操作. seleniu ...

  9. 浏览器行为模拟之requests、selenium模块

    requests模块 前言: 通常我们利用Python写一些WEB程序.webAPI部署在服务端,让客户端request,我们作为服务器端response数据: 但也可以反主为客利用Python的re ...

  10. 爬虫模块之selenium模块

    一 模块的介绍 selenium模块最开始是一个自动化测试的工具,驱动浏览器完全模拟浏览器自动测试. from selenium import webdriver # 驱动浏览器 browser=we ...

随机推荐

  1. 启用k8s metrics server监控

    1.创建aggregator证书 方法一:直接使用二进制源码包安装 $ wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64 $ chmod +x cfs ...

  2. 【算法】螺旋方阵 上交OJ1021

    输入格式: 输入在一行中给出一个正整数N(<10). 输出格式: 输出N×N的螺旋方阵.每行N个数字,每个数字占3位. 输入样例: 5 1 2 3 4 5 16 17 18 19 6 15 24 ...

  3. 【动态规划】 EditDistance

    思路参考: https://www.cnblogs.com/littlepanpc/p/7895810.html 代码参考:https://leetcode.com/problems/edit-dis ...

  4. svg-sprite使用

    chainWebpack(config) { config.module .rule('svg') .exclude.add(path.resolve(__dirname,'src/assets/ic ...

  5. 利用Python查看微信共同好友

    思路 首先通过itchat这个微信个人号接口扫码登录个人微信网页版,获取可以识别好友身份的数据.这里是需要分别登录两人微信的,拿到两人各自的好友信息存到列表中. 这样一来,查共同好友就转化成了查两个列 ...

  6. IntellIJ IDEA 配置 Maven 以及 修改 默认 Repository

    转自:IntellIJ IDEA 配置 Maven 以及 修改 默认 Repository 今天将IntellIJ IDEA 关于Maven的配置总结一下,方便以后可参考. IDEA版本: Intel ...

  7. 拒绝回调,拥抱async await

    之前使用jquery中ajax,请求的结果需要写在回调函数里面,后面接触到了axios/fetch,使用了es6中Promise进行封装,这种链式结构调用,看起来比之前直观,可是还是没有解决回调的问题 ...

  8. 正则化(Regularization)本质

    参考: http://www.cnblogs.com/maybe2030/p/9231231.html https://blog.csdn.net/wsj998689aa/article/detail ...

  9. Python——模块——fnmatch(文件名对比)

    一.模块作用 fnmatch 模块主要用于文件名的比较,使用 Unix shell 使用的 glob 样式模式. 二.简单匹配 fnmatch() 将单个文件名与模式进行比较并返回布尔值,来看它们是否 ...

  10. 【MT】牛津的MT教程

    Preamble This repository contains the lecture slides and course description for the Deep Natural Lan ...