該模塊最初是一個自動化測試模塊,而在爬蟲中使用它是爲了解決requests沒法直接執行JavaScript代碼的問題php
本質是驅動瀏覽器,徹底模擬瀏覽器的操做,如跳轉、輸入、點擊、下拉等css
selenium支持的多種瀏覽器:html
from selenium import webdriver browser=webdriver.Chrome() browser=webdriver.Firefox() browser=webdriver.PhantomJS() # 一個無界面的瀏覽器 browser=webdriver.Safari() browser=webdriver.Edge()
它的官方文檔連接:https://selenium-python.readthedocs.io/python
針對有界面的瀏覽器:jquery
安裝連接:http://npm.taobao.org/mirrors/chromedriver/linux
下載chromdriver.exe,把它放到python安裝路徑的scripts目錄中便可(本人windows)git
對於mac系統,將解壓後的chromedriver移動到/usr/local/bin目錄下github
而後再咱們的python中安裝pip包web
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple selenium
注意:selenium3默認支持的webdriver是Firfox,而Firefox須要安裝geckodriver 下載連接chrome
針對無界面的瀏覽器phantomjs:
#安裝:selenium+phantomjs pip3 install selenium 下載phantomjs,解壓後把phantomjs.exe所在的bin目錄放到環境變量 下載連接:http://phantomjs.org/download.html
# 該無界面的瀏覽器已經再也不提供更新,可是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() #切記關閉瀏覽器,回收資源
模擬訪問百度瀏覽器,並輸入onepiece搜索
指定一個加載後的資源做爲搜索結果
代碼
import time from selenium import webdriver from selenium.webdriver.common.by import By # 按照什麼方式去查找 from selenium.webdriver.common.keys import Keys # 鍵盤按鍵操做 from selenium.webdriver.support import expected_conditions as E 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') # 查找id=kw的標籤 input_tag.send_keys('onepiece') # 輸入關鍵字進行搜索 input_tag.send_keys(Keys.ENTER) # 回車按鈕 wait = WebDriverWait(browser, 10) # 等待資源加載 wait.until(E.presence_of_element_located((By.ID, 'container'))) # 直到當中指定id加載出來 time.sleep(3) finally: browser.close() # 關閉瀏覽器
1.基本用法
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, 10) 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')) # 搜索框id # 二、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('錄')[0] # 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('密碼') commit.click() # 提交 # 七、find_element_by_css_selector driver.find_element_by_css_selector('#kw') # 八、find_element_by_xpath time.sleep(5) finally: driver.close()
from selenium import webdriver from selenium.webdriver.common.by import By # 按照什麼方式查找,By.ID,By.CSS_SELECTOR 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, 10) 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')) # https://images-cn.ssl-images-amazon.com # /images/G/28/kindle/design/2018/Device/ys_180925_ATF1500x300_travel_dvc._CB484178544_.jpg
# 獲取標籤ID,位置,名稱,大小 print(tag.id) # 0.5932406187872517-2 print(tag.location) # {'x': 0, 'y': 0} print(tag.tag_name) # img print(tag.size) # {'height': 0, 'width': 0} browser.close()
經過控制節點,實現經過咱們的程序實現瀏覽器的交互
from selenium import webdriver import time browser = webdriver.Chrome() browser.get('https://www.taobao.com') # 打開淘寶 input = browser.find_element_by_id('q') # 查詢id屬性爲q的標籤,也就是input搜索框! input.send_keys('MAC') # 輸入文字MAC time.sleep(1) # 等待1秒 input.clear() # 清空文字 input.send_keys('IPhone') # 輸入文字IPhone # 查詢class屬性爲btn-search的標籤,它是一個button標籤 button = browser.find_element_by_class_name('btn-search') button.click() # 點擊搜索 browser.close()
將某個節點(文本)從一處拖拽到另外一處
右邊的窗口是一個iframe框架,它擁有獨立的html標籤。所以使用selenium時,須要使用switch_to.frame切換到frame才行,不然找不到
from selenium import webdriver from selenium.webdriver import ActionChains import time browser = webdriver.Chrome() url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable' browser.get(url) # 訪問網頁 browser.switch_to.frame('iframeResult') # 切換到frame,找到id爲iframeResult的元素 source = browser.find_element_by_css_selector('#draggable') # 起始標籤 target = browser.find_element_by_css_selector('#droppable') # 目的標籤 actions = ActionChains(browser) # 建立動做鏈 # actions.drag_and_drop(source, target) actions.click_and_hold(source) # 點擊鼠標左鍵,按住不放 time.sleep(0.5) # 模擬勻速運動 for i in range(5): # 移動座標,xOffset 爲橫座標,yOffset 爲縱座標 # 調用perform()方法時,隊列中的時間會依次執行。它會執行鏈中的全部動做 actions.move_by_offset(xoffset=17,yoffset=0).perform() time.sleep(0.5) actions.release() # 鬆開鼠標左鍵 browser.close()
樣式:
使用execute_script()
方法執行下拉進度條任務以及alert任務
import time from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.jd.com/') time.sleep(5) # 這樣下拉下過才比較明顯 # window.scrollTo表示右側的滑動條,括號的參數表示從上面直接拉到最底下 browser.execute_script('window.scrollTo(0, document.body.scrollHeight)') browser.execute_script('alert("123")') # 彈出123
使用back()
方法後退,使用forward()
方法前進
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.qq.com/') browser.back() # Goes one step backward in the browser history. time.sleep(1) browser.forward() # Goes one step forward in the browser history. browser.close() # Closes the current window.
使用selenium,咱們還能夠獲取,刪除,修改cookies
from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.zhihu.com/explore') # 打印知乎設置的cookie print(browser.get_cookies()) # 增長3個cookie browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'germey'}) # 打印增長以後的全部cookie print(browser.get_cookies()) # 清空此頁面的全部的cookie browser.delete_all_cookies() print(browser.get_cookies()) # [] browser.close()
操做主要是利用了灰度差,程序截取了先後兩張圖片,從左上角到右下角進行循環,進行灰度比較(RGB差值),從而找見缺口,並測出須要移動的距離。而後利用函數模擬人爲移動滑塊
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait # 等待元素加載的 from selenium.webdriver.common.action_chains import ActionChains # 拖拽 from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from PIL import Image import requests import re import random from io import BytesIO import time def merge_image(image_file, location_list): """ 拼接圖片 """ im = Image.open(image_file) im.save('code.jpg') new_im = Image.new('RGB', (260, 116)) # 把無序的圖片 切成52張小圖片 im_list_upper = [] im_list_down = [] # print(location_list) for location in location_list: # print(location['y']) if location['y'] == -58: # 上半邊 im_list_upper.append(im.crop((abs(location['x']), 58, abs(location['x']) + 10, 116))) if location['y'] == 0: # 下半邊 im_list_down.append(im.crop((abs(location['x']), 0, abs(location['x']) + 10, 58))) x_offset = 0 for im in im_list_upper: new_im.paste(im, (x_offset, 0)) # 把小圖片放到 新的空白圖片上 x_offset += im.size[0] x_offset = 0 for im in im_list_down: new_im.paste(im, (x_offset, 58)) x_offset += im.size[0] # new_im.show() return new_im def get_image(driver, div_path): ''' 下載無序的圖片 而後進行拼接 得到完整的圖片 :param driver: :param div_path: :return: ''' background_images = driver.find_elements_by_xpath(div_path) location_list = [] for background_image in background_images: location = {} result = re.findall('background-image: url\("(.*?)"\); background-position: (.*?)px (.*?)px;', background_image.get_attribute('style')) # print(result) location['x'] = int(result[0][1]) location['y'] = int(result[0][2]) image_url = result[0][0] location_list.append(location) image_url = image_url.replace('webp', 'jpg') # '替換url http://static.geetest.com/pictures/gt/579066de6/579066de6.webp' image_result = requests.get(image_url).content image_file = BytesIO(image_result) # 是一張無序的圖片 image = merge_image(image_file, location_list) return image def get_track(distance): # 初速度 v = 0 # 單位時間爲0.2s來統計軌跡,軌跡即0.2內的位移 t = 0.2 # 位移/軌跡列表,列表內的一個元素表明0.2s的位移 tracks = [] tracks_back = [] # 當前的位移 current = 0 # 到達mid值開始減速 mid = distance * 7 / 8 print("distance", distance) global random_int random_int = 8 distance += random_int # 先滑過一點,最後再反着滑動回來 while current < distance: if current < mid: # 加速度越小,單位時間的位移越小,模擬的軌跡就越多越詳細 a = random.randint(2, 5) # 加速運動 else: a = -random.randint(2, 5) # 減速運動 # 初速度 v0 = v # 0.2秒時間內的位移 s = v0 * t + 0.5 * a * (t ** 2) # 當前的位置 current += s # 添加到軌跡列表 if round(s) > 0: tracks.append(round(s)) else: tracks_back.append(round(s)) # 速度已經達到v,該速度做爲下次的初速度 v = v0 + a * t print("tracks:", tracks) print("tracks_back:", tracks_back) print("current:", current) # 反着滑動到大概準確位置 tracks_back.append(distance - current) tracks_back.extend([-2, -5, -8, ]) return tracks, tracks_back def get_distance(image1, image2): ''' 拿到滑動驗證碼須要移動的距離 :param image1:沒有缺口的圖片對象 :param image2:帶缺口的圖片對象 :return:須要移動的距離 ''' # print('size', image1.size) threshold = 50 for i in range(0, image1.size[0]): # 260 for j in range(0, image1.size[1]): # 160 pixel1 = image1.getpixel((i, j)) pixel2 = image2.getpixel((i, j)) res_R = abs(pixel1[0] - pixel2[0]) # 計算RGB差 res_G = abs(pixel1[1] - pixel2[1]) # 計算RGB差 res_B = abs(pixel1[2] - pixel2[2]) # 計算RGB差 if res_R > threshold and res_G > threshold and res_B > threshold: return i # 須要移動的距離 def main_check_code(driver, element): """ 拖動識別驗證碼 :param driver: :param element: :return: """ login_btn = driver.find_element_by_class_name('js-login') login_btn.click() element = WebDriverWait(driver, 30, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'gt_guide_tip'))) slide_btn = driver.find_element_by_class_name('gt_guide_tip') slide_btn.click() image1 = get_image(driver, '//div[@class="gt_cut_bg gt_show"]/div') image2 = get_image(driver, '//div[@class="gt_cut_fullbg gt_show"]/div') # 圖片上 缺口的位置的x座標 # 2 對比兩張圖片的全部RBG像素點,獲得不同像素點的x值,即要移動的距離 l = get_distance(image1, image2) print('l=', l) # 3 得到移動軌跡 track_list = get_track(l) print('第一步,點擊滑動按鈕') element = WebDriverWait(driver, 30, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'gt_slider_knob'))) ActionChains(driver).click_and_hold(on_element=element).perform() # 點擊鼠標左鍵,按住不放 import time time.sleep(0.4) print('第二步,拖動元素') for track in track_list[0]: ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform() # 鼠標移動到距離當前位置(x,y) # time.sleep(0.4) for track in track_list[1]: ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform() # 鼠標移動到距離當前位置(x,y) time.sleep(0.1) import time time.sleep(0.6) # ActionChains(driver).move_by_offset(xoffset=2, yoffset=0).perform() # 鼠標移動到距離當前位置(x,y) # ActionChains(driver).move_by_offset(xoffset=8, yoffset=0).perform() # 鼠標移動到距離當前位置(x,y) # ActionChains(driver).move_by_offset(xoffset=2, yoffset=0).perform() # 鼠標移動到距離當前位置(x,y) print('第三步,釋放鼠標') ActionChains(driver).release(on_element=element).perform() time.sleep(1) def main_check_slider(driver): """ 檢查滑動按鈕是否加載 :param driver: :return: """ while True: try: driver.get('https://www.huxiu.com/') element = WebDriverWait(driver, 30, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'js-login'))) if element: return element except TimeoutException as e: print('超時錯誤,繼續') time.sleep(5) if __name__ == '__main__': try: count = 3 # 最多識別3次 driver = webdriver.Chrome() while count > 0: # 等待滑動按鈕加載完成 element = main_check_slider(driver) main_check_code(driver, element) try: success_element = (By.CSS_SELECTOR, '.gt_success') # 獲得成功標誌 success_images = WebDriverWait(driver, 3).until(EC.presence_of_element_located(success_element)) if success_images: print('成功識別!!!!!!') count = 0 import sys sys.exit() except Exception as e: print('識別錯誤,繼續') count -= 1 time.sleep(1) else: print('too many attempt check code ') exit('退出程序') finally: driver.close()
具體介紹參考祥哥博客
也可參考CSDN連接