爬蟲 無頭瀏覽器 規避監測


無頭瀏覽器

- phantomJs:無可視化界面的瀏覽器
- 谷歌無頭瀏覽器:
from selenium.webdriver.chrome.options import Options。
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
browser = webdriver.Chrome(executable_path=path, chrome_options=chrome_options)

# 無頭瀏覽器舉例
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from time import sleep
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')

bro = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)

bro.get('https://www.baidu.com')
sleep(3)
print(bro.page_source)
bro.save_screenshot('1.png')

bro.quit()

規避監測

現在不少大網站有對selenium采取了監測機制。比如正常情況下我們用瀏覽器訪問淘寶等網站的 window.navigator.webdriver的值為 
undefined。而使用selenium訪問則該值為true。那么如何解決這個問題呢?

只需要設置Chromedriver的啟動參數即可解決問題。在啟動Chromedriver之前,為Chrome開啟實驗性功能參數excludeSwitches,它的值為['enable-automation'],完整代碼如下:

from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions

option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)

 

- 相關的網站會對selenium發起的請求進行監測 - 網站后台可以根據window.navigator.webdriver返回值進行selenium的監測
- undefinded:不是selenium進行的請求發送
- true:是selenium發起的請求
- 規避監測的方法:
from selenium.webdriver import ChromeOptions
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
bro = webdriver.Chrome(executable_path='chromedriver.exe',options=option)

from selenium import webdriver
from selenium.webdriver import ChromeOptions
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
#實現了規避監測
bro = webdriver.Chrome(executable_path='chromedriver.exe',options=option)
bro.get('https://www.taobao.com/')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM