一直在學習scrapy的爬蟲知識,可是遇到了動態加載頁面的難題,從一開始的javascript渲染器--splash,docker服務,javascript
遇到各類奇葩的問題:php
1.docker代理設置添加無效,致使沒法拉取splash鏡像css
2.settings.py中開啓splash服務,致使沒法ssl鏈接java
而後看見了這個selenium,一開始不太相信有多大的功能,到接觸以後,感受很好用。就給你們稍微介紹下--python
根據selenium用法詳解:https://blog.csdn.net/qq_29186489/article/details/78661008,添加了其餘本身在學習中學習到的內容jquery
下面讓咱們開始:web
selenium 是一個用於Web應用程序測試的工具。Selenium測試直接運行在瀏覽器中,就像真正的用戶在操做同樣chrome
selenium用於爬蟲,主要是用來解決javascript渲染的問題 docker
詳細用法以下:api
1:聲明瀏覽器對象
# -*- coding: utf-8 -*-
from selenium import webdriver import pdb #聲明谷歌、Firefox、Safari等瀏覽器
browser=webdriver.Chrome() browser=webdriver.Firefox() browser=webdriver.Safari() browser=webdriver.Edge() browser=webdriver.PhantomJS()
2.訪問頁面
#_*_coding: utf-8_*_
import time from selenium import webdriver browser=webdriver.Chrome() browser.get("http://www.taobao.com") time.sleep(3) print(browser.page_source) ''' Traceback (most recent call last): File "selenium4.py", line 6, in <module> print(browser.page_source) File "C:\Users\wuchan4x\AppData\Local\Continuum\anaconda2\lib\encodings\cp1252.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode characters in position 13799-13802: character maps to <undefined> '''
print(browser.page_source.encode('utf8')) browser.close()
3.查找單個元素
#_*_coding: utf-8_*_
from selenium import webdriver from selenium.webdriver.common.by import By browser=webdriver.Chrome() browser.get("http://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.ID,"q") print(input_first,input_second,input_third) ''' (<selenium.webdriver.remote.webelement.WebElement (session="2846b0462091d95ca6da355fefd70808", element="0.12060594823778437-1")>, <selenium.webdriver.remote.webelement.WebElement (session="2846b0462091d95ca6da355fefd70808", element="0.12060594823778437-1")>, <selenium.webdriver.remote.webelement.WebElement (session="2846b0462091d95ca6da355fefd70808", element="0.12060594823778437-1")>) ''' browser.close()
4.查找多個元素
#_*_coding: utf-8_*_
from selenium import webdriver from selenium.webdriver.common.by import By browser=webdriver.Chrome() browser.get("http://www.taobao.com") lis=browser.find_element_by_css_selector("li") lis_c=browser.find_element(By.CSS_SELECTOR,"li") #(<selenium.webdriver.remote.webelement.WebElement (session="f326ff15fb184846950679a37c7bc437", element="0.8927328599507083-2")>, #<selenium.webdriver.remote.webelement.WebElement (session="f326ff15fb184846950679a37c7bc437", element="0.8927328599507083-2")>)
print(lis,lis_c) browser.close()
5:元素的交互操做
對獲取到的元素調用交互方法
#_*_coding: utf-8_*_
from selenium import webdriver import time browser=webdriver.Chrome() browser.get("https://www.taobao.com") #input=browser.find_element_by_id("q") #input=browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[2]/div[3]/div/input')
input=browser.find_element_by_class_name("search-combobox-input") input.send_keys("iPhone") browser.save_screenshot('iphone.png') time.sleep(10) input.clear() input.send_keys("iPad") button=browser.find_element_by_class_name("btn-search") button.click() time.sleep(10) browser.close()
6:交互動做
把動做附加到交互鏈中
#_*_coding: utf-8_*_
from selenium import webdriver from selenium.webdriver import ActionChains import time from selenium.webdriver.common.alert import Alert browser=webdriver.Chrome() url="http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable" browser.get(url) #切換到目標元素所在的frame
browser.switch_to.frame("iframeResult") #肯定拖拽目標的起點
source=browser.find_element_by_id("draggable") #肯定拖拽目標的終點
target=browser.find_element_by_id("droppable") #造成動做鏈
actions=ActionChains(browser) actions.drag_and_drop(source,target) #執行
actions.perform() ''' 1.先用switch_to_alert()方法切換到alert彈出框上 2.能夠用text方法獲取彈出的文本 信息 3.accept()點擊確認按鈕 4.dismiss()至關於點右上角x,取消彈出框 ''' t=browser.switch_to_alert() print(t.text) t.accept() time.sleep(10) browser.close()
7:執行javascript
下面的例子是執行就是,拖拽進度條到底,並彈出提示框
#_*_coding: utf-8_*_
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 Button')") browser.close()
8:獲取元素信息
獲取屬性
# -*- coding: utf-8 -*-
from selenium import webdriver browser=webdriver.Chrome() url='https://www.zhihu.com/explore' browser.get(url) browser.implicitly_wait(10) logo=browser.find_element_by_id('zh-top-link-logo') print(logo) #<selenium.webdriver.remote.webelement.WebElement (session="4d57a638f4970f803c603c8fd677f77a", element="0.949410104143495-1")>
print(logo.id) #0.949410104143495-1
print(logo.size) #{'width': 61, 'height': 45}
print(logo.location) #{'y': 0.0, 'x': 10.0}
print(logo.tag_name) #a
print(logo.text) #u'\u77e5\u4e4e'
browser.close()
9:等待
隱式等待
當使用了隱式等待執行測試的時候,若是webdriver沒有在DOM中找到元素,將繼續等待,超過設定的時間後則拋出找不到元素的異常,換句話說,當查找元素或元素並無當即出現的時候,隱式等待將等待一段時間再查找DOM,默認時間爲0.
# -*- coding: utf-8 -*-
from selenium import webdriver browser=webdriver.Chrome() url="https://www.zhihu.com/explore" browser.get(url) browser.implicitly_wait(10) logo=browser.find_element_by_id("zh-top-link-logo") print(logo) browser.close()
顯示等待
# -*- coding: utf-8 -*-
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() url="https://www.taobao.com" browser.get(url) 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) browser.close()
10:瀏覽器的前進和後退
# -*- coding: utf-8 -*-
from selenium import webdriver import time browser=webdriver.Chrome() browser.get("https://www.taobao.com") browser.get("https://www.baidu.com") browser.get("https://www.python.org") browser.back() time.sleep(1) browser.forward() browser.close()
11:cookies的處理
# -*- coding: utf-8 -*-
from selenium import webdriver import time browser=webdriver.Chrome() browser.get("https://www.zhihu.com/explore") print(browser.get_cookies()) browser.add_cookie({"name":"name","domain":"www.zhihu.com","value":"germey"}) print(browser.get_cookies()) browser.delete_all_cookies() print(browser.get_cookies()) browser.close()
12:選項卡管理
# -*- coding: utf-8 -*-
from selenium import webdriver import time browser=webdriver.Chrome() browser.get("https://www.zhihu.com/explore") browser.execute_script("window.open()") print(browser.window_handles) browser.switch_to_window(browser.window_handles[1]) browser.get("https://www.taobao.com") time.sleep(1) browser.switch_to_window(browser.window_handles[0]) browser.get("https://python.org") browser.close()
13:異常處理
# -*- coding: utf-8 -*-
from selenium import webdriver from selenium.common.exceptions import TimeoutException,NoSuchElementException browser=webdriver.Chrome() try: browser.get("https://www.zhihu.com/explore") except TimeoutException: print("Time out") try: browser.find_element_by_id("hello") except NoSuchElementException: print("No Element") finally: browser.close()
備註(遇到的問題與解決辦法):
File"C:\Users\wuchan4x\AppData\Local\Continuum\anaconda2\lib\site-packages\selenium-3.14.0-py2.7.egg\selenium\webdriver\common\service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home 解決辦法:將chomedriver.exe放入運行python文件目錄下 Traceback (most recent call last): File "login_.py", line 22, in <module> print(data) File "C:\Users\wuchan4x\AppData\Local\Continuum\anaconda2\lib\encodings\cp1252.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1: character maps to <undefined> 解決辦法:Print(data.encode('utf-8'))
查找元素
input=browser.find_element_by_id("q")
input=browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[2]/div[3]/div/input')
input=browser.find_element_by_class_name("search-combobox-input")
driver.find_element_by_name('t2').get_attribute('value')
driver.find_element_by_xpath('//input[@value="dbl click me"]')
driver.find_element_by_xpath('//textarea[@name="t2"]').get_attribute('value')#獲取文本框中的內容
driver.find_element_by_name('t2').get_attribute('value')
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
鼠標操做
click(on_element=None) ——單擊鼠標左鍵
click_and_hold(on_element=None) ——點擊鼠標左鍵,不鬆開
context_click(on_element=None) ——點擊鼠標右鍵
double_click(on_element=None) ——雙擊鼠標左鍵
drag_and_drop(source, target) ——拖拽到某個元素而後鬆開
drag_and_drop_by_offset(source, xoffset, yoffset) ——拖拽到某個座標而後鬆開
key_down(value, element=None) ——按下某個鍵盤上的鍵
key_up(value, element=None) ——鬆開某個鍵
move_by_offset(xoffset, yoffset) ——鼠標從當前位置移動到某個座標
move_to_element(to_element) ——鼠標移動到某個元素
move_to_element_with_offset(to_element, xoffset, yoffset) ——移動到距某個元素(左上角座標)多少距離的位置
perform() ——執行鏈中的全部動做
release(on_element=None) ——在某個元素位置鬆開鼠標左鍵
send_keys(*keys_to_send) ——發送某個鍵到當前焦點的元素
send_keys_to_element(element, *keys_to_send) ——發送某個鍵到指定元素