请求库之 selenium模块

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

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

  1 from selenium import webdriver
  2 browser=webdriver.Chrome()
  3 browser=webdriver.Firefox()
  4 browser=webdriver.PhantomJS()  #无窗口浏览器
  5 browser=webdriver.Safari()
  6 browser=webdriver.Edge()

二、安装

安装:selenium+chromedriver

  1 pip3 install selenium
  2 下载chromdriver.exe放到python安装路径的scripts目录中即可
  3 	国内镜像网站地址:http://npm.taobao.org/mirrors/chromedriver/2.29/
  4 	最新的版本去官网找:https://sites.google.com/a/chromium.org/chromedriver/downloads
  5 
  6 #验证安装
  7 在cmd中输入python
  8 C:>python3
  9 Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
 10 Type "help", "copyright", "credits" or "license" for more information.
 11 >>> from selenium import webdriver
 12 >>> driver=webdriver.Chrome() #弹出浏览器
 13 >>> driver.get('https://www.baidu.com')
 14 >>> driver.page_source
 15 
 16 #注意:
 17 	selenium3默认支持的webdriver是Firfox,而Firefox需要安装geckodriver
 18 	下载链接:https://github.com/mozilla/geckodriver/releases

安装:selenium+phantomjs
  1 pip3 install selenium
  2 下载phantomjs,解压后把phantomjs.exe所在的bin目录放到环境变量
  3 下载链接:http://phantomjs.org/download.html
  4 
  5 #验证安装
  6 在cmd中输入phantomjs
  7 C:>phantomjs
  8 phantomjs> console.log('egon gaga')
  9 egon gaga
 10 undefined
 11 phantomjs> ^C
 12 
 13 C:>python3
 14 Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
 15 Type "help", "copyright", "credits" or "license" for more information.
 16 >>> from selenium import webdriver
 17 >>> driver=webdriver.PhantomJS() #无界面浏览器
 18 >>> driver.get('https://www.baidu.com')
 19 >>> driver.page_source
 20 

三、基本使用
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains   #破解活动验证码的时候用到
  3 from selenium.webdriver.common.by import By   ##按照什么方式查找,By.ID,By.CSS_SELECTOR
  4 from selenium.webdriver.common.keys import Keys  #键盘按键操作
  5 from selenium.webdriver.support import expected_conditions as EC  #这个下面的一个是配合来使用的
  6 from selenium.webdriver.support.wait import WebDriverWait  #等待页面加载某些元素
  7 browser = webdriver.Chrome()  # 弹出浏览器
  8 try:
  9     browser.get("https://ai.taobao.com/")  #打开要访问的页面
 10     input_tag = browser.find_element_by_id("key")  #找到搜索框
 11     input_tag.send_keys("生日礼物") #输入内容
 12     input_tag.send_keys(Keys.ENTER) #按回车
 13     wait = WebDriverWait(browser,10)
 14     wait.until(EC.presence_of_element_located((By.CLASS_NAME,"waterfall-bg"))) #等到class为waterfall-bg的元素加载完毕(也就是等加载的内容加载完),
 15 最多等10秒
 16 
 17 
 18     print(browser.page_source)
 19     print(browser.current_url)
 20     print(browser.get_cookies())
 21 except Exception as error:
 22     print(error)
 23 finally:
 24     browser.close()
四、选择器
   基本用法
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains
  3 from selenium.webdriver.common.by import By
  4 from selenium.webdriver.common.keys import Keys
  5 from selenium.webdriver.support import expected_conditions as EC
  6 from selenium.webdriver.support.wait import WebDriverWait
  7 import time
  8 
  9 driver = webdriver.Chrome()
 10 driver.get("https://www.baidu.com")
 11 wait = driver.implicitly_wait(10)  #隐式等待,等所有,默认等10秒
 12 
 13 #显示等待的用法
 14 # wait = WebDriverWait(driver,10)  #显示等待,等指定的,和EC配合这使用
 15 # wait.until(EC.presence_of_element_located((By.ID,"kw")))
 16 # 如果显示等待是不能进行点击的,如果要点击,就得按照下面这样的方式,而隐式等待就不用考虑这个问题了。
 17 # button = wait.until(EC.element_to_be_clickable((By.ID,"kw")))
 18 # button.click()
 19 try:
 20     # 1、find_element_by_id通过id来找
 21     # tag = driver.find_element_by_id("su")
 22     # print(tag.get_attribute("value"))  #获取上面这个标签的属性
 23     # 2、find_element_by_link_text通过有链接的文本去找
 24     # login = driver.find_element_by_link_text("登录")
 25     # print(login.get_attribute("href"))
 26     # login.click()  #点击登录按钮
 27     # 3、find_element_by_partial_link_text 找到包含这个录字的链接文本去找
 28     # login =  driver.find_element_by_partial_link_text("")
 29     # login.click()
 30     # 4、find_element_by_tag_name通过标签的名字去找
 31     # print(driver.find_element_by_tag_name("a"))
 32     # time.sleep(5)
 33     # 5、find_element_by_class_name通过类名去找
 34     # print(driver.find_element_by_class_name("tang-pass-footerBarULogin"))
 35    # 6、通过css选择器找
 36    print(driver.find_element_by_css_selector("#kw"))
 37 finally:
 38     driver.quit()
xpath
  1 #官网链接:http://selenium-python.readthedocs.io/locating-elements.html
  2 from selenium import webdriver
  3 from selenium.webdriver import ActionChains
  4 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
  5 from selenium.webdriver.common.keys import Keys #键盘按键操作
  6 from selenium.webdriver.support import expected_conditions as EC
  7 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
  8 import time
  9 
 10 driver=webdriver.PhantomJS()
 11 driver.get('https://doc.scrapy.org/en/latest/_static/selectors-sample1.html')
 12 # wait=WebDriverWait(driver,3)
 13 driver.implicitly_wait(3) #使用隐式等待
 14 
 15 try:
 16     # find_element_by_xpath
 17     #//与/
 18     # driver.find_element_by_xpath('//body/a')  # 开头的//代表从整篇文档中寻找,body之后的/代表body的儿子,这一行找不到就会报错了
 19 
 20     driver.find_element_by_xpath('//body//a')  # 开头的//代表从整篇文档中寻找,body之后的//代表body的子子孙孙
 21     driver.find_element_by_css_selector('body a')
 22 
 23     #取第n个
 24     res1=driver.find_elements_by_xpath('//body//a[1]') #取第一个a标签
 25     print(res1[0].text)
 26 
 27     #按照属性查找,下述三者查找效果一样
 28     res1=driver.find_element_by_xpath('//a[5]')
 29     res2=driver.find_element_by_xpath('//a[@href="image5.html"]')
 30     res3=driver.find_element_by_xpath('//a[contains(@href,"image5")]') #模糊查找
 31     print('==>', res1.text)
 32     print('==>',res2.text)
 33     print('==>',res3.text)
 34 
 35 
 36     #其他
 37     res1=driver.find_element_by_xpath('/html/body/div/a')
 38     print(res1.text)
 39 
 40     res2=driver.find_element_by_xpath('//a[img/@src="image3_thumb.jpg"]') #找到子标签img的src属性为image3_thumb.jpg的a标签
 41     print(res2.tag_name,res2.text)
 42 
 43     res3 = driver.find_element_by_xpath("//input[@name='continue'][@type='button']") #查看属性name为continue且属性type为button的input标签
 44     res4 = driver.find_element_by_xpath("//*[@name='continue'][@type='button']") #查看属性name为continue且属性type为button的所有标签
 45 
 46 
 47     time.sleep(5)
 48 
 49 finally:
 50     driver.close()
获取标签属性
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains
  3 from selenium.webdriver.common.by import By 		#按照什么方式查找,By.ID,By.CSS_SELECTOR
  4 from selenium.webdriver.common.keys import Keys 	#键盘按键操作
  5 from selenium.webdriver.support import expected_conditions as EC
  6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
  7 
  8 browser=webdriver.Chrome()
  9 
 10 browser.get('https://www.amazon.cn/')
 11 
 12 wait=WebDriverWait(browser,10)
 13 wait.until(EC.presence_of_element_located((By.ID,'cc-lm-tcgShowImgContainer')))
 14 
 15 tag=browser.find_element(By.CSS_SELECTOR,'#cc-lm-tcgShowImgContainer img')
 16 
 17 #获取标签属性,
 18 print(tag.get_attribute('src'))
 19  
 20 #获取标签ID,位置,名称,大小(了解)
 21 print(tag.id)
 22 print(tag.location)
 23 print(tag.tag_name)
 24 print(tag.size)
 25 
 26 browser.close()
等待元素被加载
  1 1、selenium只是模拟浏览器的行为,而浏览器解析页面是需要时间的(执行css,js),一些元素可能需要过一段时间才能加载出来,为了保证能查找到元素,必须等待
  2 
  3 #2、等待的方式分两种:
  4 隐式等待:在browser.get('xxx')前就设置,针对所有元素有效
  5 显式等待:在browser.get('xxx')之后设置,只针对某个元素有效
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains
  3 from selenium.webdriver.common.by import By 		#按照什么方式查找,By.ID,By.CSS_SELECTOR
  4 from selenium.webdriver.common.keys import Keys 	#键盘按键操作
  5 from selenium.webdriver.support import expected_conditions as EC
  6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
  7 
  8 browser=webdriver.Chrome()
  9 
 10 #隐式等待:在查找所有元素时,如果尚未被加载,则等10秒
 11 browser.implicitly_wait(10)
 12 
 13 browser.get('https://www.baidu.com')
 14 
 15 input_tag=browser.find_element_by_id('kw')
 16 input_tag.send_keys('美女')
 17 input_tag.send_keys(Keys.ENTER)
 18 
 19 contents=browser.find_element_by_id('content_left') #没有等待环节而直接查找,找不到则会报错
 20 print(contents)
 21 
 22 browser.close()
 23 
 24 
隐式等待 View Code
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains
  3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
  4 from selenium.webdriver.common.keys import Keys #键盘按键操作
  5 from selenium.webdriver.support import expected_conditions as EC
  6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
  7 
  8 browser=webdriver.Chrome()
  9 browser.get('https://www.baidu.com')
 10 
 11 
 12 input_tag=browser.find_element_by_id('kw')
 13 input_tag.send_keys('美女')
 14 input_tag.send_keys(Keys.ENTER)
 15 
 16 #显式等待:显式地等待某个元素被加载
 17 wait=WebDriverWait(browser,10)
 18 wait.until(EC.presence_of_element_located((By.ID,'content_left')))
 19 
 20 contents=browser.find_element(By.CSS_SELECTOR,'#content_left')
 21 print(contents)
 22 
 23 
 24 browser.close()
 25 
 26 
显式等待 View Code
元素交互操作
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains
  3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
  4 from selenium.webdriver.common.keys import Keys #键盘按键操作
  5 from selenium.webdriver.support import expected_conditions as EC
  6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
  7 
  8 browser=webdriver.Chrome()
  9 browser.get('https://www.amazon.cn/')
 10 wait=WebDriverWait(browser,10)
 11 
 12 
 13 input_tag=wait.until(EC.presence_of_element_located((By.ID,'twotabsearchtextbox')))
 14 input_tag.send_keys('iphone 8')
 15 button=browser.find_element_by_css_selector('#nav-search > form > div.nav-right > div > input')
 16 button.click()
 17 
 18 import time
 19 time.sleep(3)
 20 
 21 input_tag=browser.find_element_by_id('twotabsearchtextbox')
 22 input_tag.clear() #清空输入框
 23 input_tag.send_keys('iphone7plus')
 24 button=browser.find_element_by_css_selector('#nav-search > form > div.nav-right > div > input')
 25 button.click()
 26 
 27 
 28 # browser.close()
 29 
点击,清空 View Code
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains
  3 from selenium.webdriver.common.by import By  # 按照什么方式查找,By.ID,By.CSS_SELECTOR
  4 from selenium.webdriver.common.keys import Keys  # 键盘按键操作
  5 from selenium.webdriver.support import expected_conditions as EC
  6 from selenium.webdriver.support.wait import WebDriverWait  # 等待页面加载某些元素
  7 import time
  8 
  9 driver = webdriver.Chrome()
 10 driver.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
 11 wait=WebDriverWait(driver,3)
 12 # driver.implicitly_wait(3)  # 使用隐式等待
 13 
 14 try:
 15     driver.switch_to.frame('iframeResult') ##切换到iframeResult
 16     sourse=driver.find_element_by_id('draggable')
 17     target=driver.find_element_by_id('droppable')
 18 
 19     #方式一:基于同一个动作链串行执行
 20     # actions=ActionChains(driver) #拿到动作链对象
 21     # actions.drag_and_drop(sourse,target) #把动作放到动作链中,准备串行执行
 22     # actions.perform()
 23 
 24     #方式二:不同的动作链,每次移动的位移都不同
 25     ActionChains(driver).click_and_hold(sourse).perform()
 26     distance=target.location['x']-sourse.location['x']
 27 
 28     track=0
 29     while track < distance:
 30         ActionChains(driver).move_by_offset(xoffset=2,yoffset=0).perform()
 31         track+=2
 32 
 33     ActionChains(driver).release().perform()
 34 
 35     time.sleep(10)
 36 
 37 finally:
 38     driver.close()
Action Chains View Code
  在交互动作比较难实现的时候可以自己写JS(万能方法)
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains
  3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
  4 from selenium.webdriver.common.keys import Keys #键盘按键操作
  5 from selenium.webdriver.support import expected_conditions as EC
  6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
  7 
  8 try:
  9     browser=webdriver.Chrome()
 10     browser.get('https://www.baidu.com')
 11     browser.execute_script('alert("hello world")') #打印警告
 12 finally:
 13     browser.close()
 14
  1 #frame相当于一个单独的网页,在父frame里是无法直接查看到子frame的元素的,必须switch_to_frame切到该frame下,才能进一步查找
  2 
  3 from selenium import webdriver
  4 from selenium.webdriver import ActionChains
  5 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
  6 from selenium.webdriver.common.keys import Keys #键盘按键操作
  7 from selenium.webdriver.support import expected_conditions as EC
  8 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
  9 
 10 
 11 try:
 12     browser=webdriver.Chrome()
 13     browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
 14 
 15     browser.switch_to.frame('iframeResult') #切换到id为iframeResult的frame
 16 
 17     tag1=browser.find_element_by_id('droppable')
 18     print(tag1)
 19 
 20     # tag2=browser.find_element_by_id('textareaCode') #报错,在子frame里无法查看到父frame的元素
 21     browser.switch_to.parent_frame() #切回父frame,就可以查找到了
 22     tag2=browser.find_element_by_id('textareaCode')
 23     print(tag2)
 24 
 25 finally:
 26     browser.close()
 27 
frame的切换 View Code
   模拟浏览器的前进后退
  1 import time
  2 from selenium import webdriver
  3 
  4 browser=webdriver.Chrome()
  5 browser.get('https://www.baidu.com')
  6 browser.get('https://www.taobao.com')
  7 browser.get('http://www.sina.com.cn/')
  8 
  9 browser.back()
 10 time.sleep(10)
 11 browser.forward()
 12 browser.close()
 13 
    cookies
  1 from selenium import webdriver
  2 
  3 browser=webdriver.Chrome()
  4 browser.get('https://www.zhihu.com/explore')
  5 print(browser.get_cookies())
  6 browser.add_cookie({'k1':'xxx','k2':'yyy'})
  7 print(browser.get_cookies())
  8 
  9 # browser.delete_all_cookies()
 10 
选项卡管理:

    切换选项卡,有js的方式windows.open,有windows快捷键:ctrl+t等,最通用的就是js的方式

  1 import time
  2 from selenium import webdriver
  3 
  4 browser=webdriver.Chrome()
  5 browser.get('https://www.baidu.com')
  6 browser.execute_script('window.open()')
  7 
  8 print(browser.window_handles) #获取所有的选项卡
  9 browser.switch_to_window(browser.window_handles[1])
 10 browser.get('https://www.taobao.com')
 11 time.sleep(10)
 12 browser.switch_to_window(browser.window_handles[0])
 13 browser.get('https://www.sina.com.cn')
 14 browser.close()
异常处理
  1 from selenium import webdriver
  2 from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException
  3 
  4 try:
  5     browser=webdriver.Chrome()
  6     browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
  7     browser.switch_to.frame('iframssseResult')
  8 
  9 except TimeoutException as e:
 10     print(e)
 11 except NoSuchFrameException as e:
 12     print(e)
 13 finally:
 14     browser.close()
 15 
  1 from selenium import webdriver
  2 from selenium.webdriver import ActionChains
  3 from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
  4 from selenium.webdriver.common.keys import Keys #键盘按键操作
  5 from selenium.webdriver.support import expected_conditions as EC
  6 from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
  7 import time
  8 
  9 
 10 def get_goods(driver):
 11     try:
 12         goods=driver.find_elements_by_class_name('gl-item')
 13 
 14         for good in goods:
 15             detail_url=good.find_element_by_tag_name('a').get_attribute('href')
 16 
 17             p_name=good.find_element_by_css_selector('.p-name em').text.replace('
','')
 18             price=good.find_element_by_css_selector('.p-price i').text
 19             p_commit=good.find_element_by_css_selector('.p-commit a').text
 20 
 21             msg = '''
 22             商品 : %s
 23             链接 : %s
 24             价钱 :%s
 25             评论 :%s
 26             ''' % (p_name,detail_url,price,p_commit)
 27 
 28             print(msg,end='

')
 29 
 30 
 31         button=driver.find_element_by_partial_link_text('下一页')
 32         button.click()
 33         time.sleep(1)
 34         get_goods(driver)
 35     except Exception:
 36         pass
 37 
 38 def spider(url,keyword):
 39     driver = webdriver.Chrome()
 40     driver.get(url)
 41     driver.implicitly_wait(3)  # 使用隐式等待
 42     try:
 43         input_tag=driver.find_element_by_id('key')
 44         input_tag.send_keys(keyword)
 45         input_tag.send_keys(Keys.ENTER)
 46         get_goods(driver)
 47     finally:
 48         driver.close()
 49 
 50 
 51 if __name__ == '__main__':
 52     spider('https://www.jd.com/',keyword='iPhone8手机')
 53 
 54 
爬取京东商城商品信息 View Code

归类 : python爬虫
原文地址:https://www.cnblogs.com/lz1996/p/12043618.html