用python擷取螢幕特定位置(具體class)的圖片(多用於爬蟲時遇到的驗證碼擷取,再進行反反爬)
阿新 • • 發佈:2018-11-21
比如在爬蟲時遇到頁面顯示驗證碼驗證環節,需要先擷取到驗證碼,再識別、輸入驗證碼,完成識別過程。
以爬取zhipin.com 為例。遇到的反爬頁面顯示如下:
擷取思路:
1,用selenium開啟該反爬的頁面,截全屏
2,定位到驗證碼處,截圖儲存即可
程式碼如下:
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from PIL import Image import time def get_snap(driver): # 對目標網頁進行截圖。這裡截的是全屏 driver.save_screenshot('full_snap.png') page_snap_obj=Image.open('full_snap.png') return page_snap_obj def get_image(driver): # 對驗證碼所在位置進行定位,然後擷取驗證碼圖片 img = driver.find_element_by_class_name('code') time.sleep(2) location = img.location size = img.size left = location['x'] top = location['y'] right = left + size['width'] bottom = top + size['height'] page_snap_obj = get_snap(driver) image_obj = page_snap_obj.crop((left, top, right, bottom)) # image_obj.show() return image_obj # 得到的就是驗證碼 def start(): driver = webdriver.Chrome() driver.get('https://www.zhipin.com/captcha/popUpCaptcha?redirect=https%3A%2F%2Fwww.zhipin.com%2Fgongsi%2F38bd5c757efa4ab6331z.html%3Fka%3Dindex_rcmd_companylogo_6_custompage') # 當爬取zhipin.com 出現驗證碼時,進入任何一個公司首頁都需要驗證碼,這裡拿的是要進入網易的公司首頁時顯示的驗證連結 # wait = WebDriverWait(driver, 10) time.sleep(3) image1 = get_image(driver) # image1.show() # 可以開啟這行,檢視所擷取的驗證碼圖片是否正確 if __name__ == '__main__': start()