selenium 模塊的基本使用
問題:selenium 模塊和爬蟲之間具有怎樣的關聯?
- 便捷的獲取網站中動態加載的數據
- 便捷實現模擬登錄
什么是selenium模塊?
- 基於瀏覽器自動化的一個模塊。
selenium模塊的使用流程:
- 環境安裝:pip install selenium
- 下載一個瀏覽器的驅動程序(谷歌,firefox等):
- chromedriver下載路徑:http://chromedriver.storage.googleapis.com/index.html
- 根據對應的chrome版本下載對應的chromedriver版本
- 實例化一個瀏覽器對象
- bro = webdriver.Chrome(executable_path='./chromedriver.exe')
- 編寫基於瀏覽器自動化的操作代碼
- 發起請求:get(url)
- 標簽定位:find系列的方法
- 標簽交互:send_keys('xxxxxxxx')
- 執行js程序:execute_script('xxxxxxxxx')
- 前進、后退:back()、forward()
- 關閉瀏覽器:close()
- selenium 處理iframe:
- 如果定位的標簽位於iframe標簽之中,則必須使用switch_to.frame(iframe的id)
- 動作鏈(拖動):from selenium.webdriver import ActionChains
- 實例化一個動作鏈對象:action = ActionChains(bro)
- click_and_hold(div):長按點擊操作
- move_by_offset(x,y)
- perform():讓動作鏈立即執行
- action.release()釋放動作鏈對象
谷歌無頭瀏覽器+規避檢測
例:
from selenium import webdriver # 實現無可視化界面 from selenium.webdriver.chrome.options import Options # 實現規避檢測 from selenium.webdriver import ChromeOptions def main(): # 實現無可視化界面的操作 chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') # 實現規避檢測 option = ChromeOptions() option.add_experimental_option('excludeSwitches', ['enable-automation']) bro = webdriver.Chrome(executable_path='./chromedriver.exe', chrome_options=chrome_options, options=option) bro.get('https://www.baidu.com/') print(bro.page_source) if __name__ == '__main__': main()
options配置屬性:
- options.add_argument(‘headless’) # 無頭模式
- options.add_argument(‘window-size={}x{}’.format(width, height)) # 直接配置大小和set_window_size一樣
- options.add_argument(‘disable-gpu’) # 禁用GPU加速
- options.add_argument(‘proxy-server={}’.format(self.proxy_server)) # 配置代理
- options.add_argument(’–no-sandbox’) # 沙盒模式運行
- options.add_argument(’–disable-setuid-sandbox’) # 禁用沙盒
- options.add_argument(’–disable-dev-shm-usage’) # 大量渲染時候寫入/tmp而非/dev/shm
- options.add_argument(’–user-data-dir={profile_path}’.format(profile_path)) # 用戶數據存入指定文件
- options.add_argument('no-default-browser-check) # 不做瀏覽器默認檢查
- options.add_argument("–disable-popup-blocking") # 允許彈窗
- options.add_argument("–disable-extensions") # 禁用擴展
- options.add_argument("–ignore-certificate-errors") # 忽略不信任證書
- options.add_argument("–no-first-run") # 初始化時為空白頁面
- options.add_argument(’–start-maximized’) # 最大化啟動
- options.add_argument(’–disable-notifications’) # 禁用通知警告
- options.add_argument(’–enable-automation’) # 通知(通知用戶其瀏覽器正由自動化測試控制)
- options.add_argument(’–disable-xss-auditor’) # 禁止xss防護
- options.add_argument(’–disable-web-security’) # 關閉安全策略
- options.add_argument(’–allow-running-insecure-content’) # 允許運行不安全的內容
- options.add_argument(’–disable-webgl’) # 禁用webgl
- options.add_argument(’–homedir={}’) # 指定主目錄存放位置
- options.add_argument(’–disk-cache-dir={臨時文件目錄}’) # 指定臨時文件目錄
- options.add_argument(‘disable-cache’) # 禁用緩存
- options.add_argument(‘excludeSwitches’, [‘enable-automation’]) # 開發者模式