Selenium的一些技巧与错误处理

        关于Selenium大家都比较熟悉了,是一个非常不错的自动化工具,用处非常大,好处就不多说了,对于这个不是很熟悉的伙伴们,可以先阅读它的基础用法:

Selenium 自动测试软件的使用(自动化操作)https://blog.csdn.net/weixin_41896770/article/details/115610884        这节主要是一些技巧的介绍,平时也会常用到,比如修改浏览器的用户代理,也就是伪造User-Agent,比如模拟手机访问。还有一些情况,就是不确定的错误,但是不希望程序跳出,而是忽略错误,继续处理,比如网速慢,页面还没有加载完,这个时候获取不到元素等一些未知情况的处理。比如就算sleep停几秒钟,让页面渲染完,可能还存在一些其他元素覆盖住了需要点击的元素!

另外还有一些站点是防止使用Selenium的情况,一般都是查看window.navigator.webdriver,如果是true,就表示使用Selenium在操作了。

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()
#模拟iPhoneX访问
#mobile={'deviceName':'iPhone X'}
#options.add_experimental_option('mobileEmulation', mobile)
#去掉Chrome正受到自动测试软件的控制
options.add_experimental_option('excludeSwitches', ['enable-automation'])
browser=webdriver.Chrome(executable_path='E:\MyChromeDriver\chromedriver.exe', chrome_options=options)

#可以彻底解决webdriver为false
browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": "Object.defineProperty(navigator, 'webdriver', {get: () => false})"})

browser.get('https://www.baidu.com')
i=0

#忽略错误
# while(True):
    # print('ok'+str(i))
    # i+=1
    # 1/0
    # if i>5:break
while(True):
    try:
        print('ok'+str(i))
        i+=1
        1/0
        if i>5:break
    except:
        pass
        if i>5:break



'''
window.navigator.webdriver为true就代表是selenium在访问
修改为false,就是正常浏览器访问了
不过缺点是在加载页面之后修改的值,pass掉
'''
#js='Object.defineProperties(navigator,{webdriver: {get: () => false,}});'
#browser.execute_script(js)


#Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1

#var customUserAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36';
#Object.defineProperty(navigator, 'userAgent', {value: customUserAgent,writable: false});

由于本人浏览器更新了,这个时候会出现下面的错误:

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 93
Current browser version is 97.0.4692.71 with binary path C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

也就是ChromeDriver 版本低了,这个时候需要下载新的对应版本

Guess you like

Origin blog.csdn.net/weixin_41896770/article/details/122469543