[ selenium防检测 ]


selenium防检测

配合unittest使用实例

from django.test import TestCase
from selenium import webdriver
import time


class UserAuthTestCase(TestCase):
    @classmethod
    def setUpClass(cls):
        print("开始")

    @classmethod
    def tearDownClass(cls):
        print("结束")

    def setUp(self):
        options = webdriver.ChromeOptions()
        # options.add_argument("--headless")  # 无头
        options.add_argument("disable-blink-features=AutomationControlled")
        options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # option.add_argument(r'--user-data-dir=C:\Users\honor\AppData\Local\Google\Chrome\User Data')  # 读取cookie
        options.add_argument(
           'user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')

        self.web = webdriver.Chrome(options=options)

        # 方法1: 读取js文件隐藏, 但是新开窗口不行
        with open('./conf/stealth.min.js', mode='r') as f:
            js = f.read()
        self.web.execute_cdp_cmd(
            cmd_args={'source': js},
            cmd="Page.addScriptToEvaluateOnNewDocument",
        )
        # 方法2: 只能规避一个
        # self.web.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        #     "source": """
        #     Object.defineProperty(navigator, 'webdriver', {
        #       get: () => false
        #     })
        #   """
        # })

    def tearDown(self) -> None:
        self.web.close()

    def test_animals_can_speak(self):
        print("运行测试1")
        self.web.get("https://bot.sannysoft.com/")
        self.web.execute_script('window.open("https://bot.sannysoft.com/")')
        # self.web.get("https://bot.sannysoft.com/")
        time.sleep(50)