100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python接管已经打开ie浏览器_使用selenium控制(接管)已打开的浏览器(chrome) 并

python接管已经打开ie浏览器_使用selenium控制(接管)已打开的浏览器(chrome) 并

时间:2019-03-19 19:51:30

相关推荐

python接管已经打开ie浏览器_使用selenium控制(接管)已打开的浏览器(chrome) 并

在使用selenium进行自动化测试中我们有时会遇到这样的情况:

我们需要手动打开浏览器,进入到所需的页面,执行一些手动任务,如输入表单、输入验证码,登陆成功后,然后再开始运行自动化脚本。

这种情况下如何使用selenium来接管先前已打开的浏览器呢?

这里给出Google Chrome浏览器的解决方案。

我们可以利用Chrome DevTools协议。它允许客户检查和调试Chrome浏览器。

打开cmd,在命令行中输入命令:

chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile"

对于-remote-debugging-port值,可以指定任何打开的端口。

对于-user-data-dir标记,指定创建新Chrome配置文件的目录。它是为了确保在单独的配置文件中启动chrome,不会污染你的默认配置文件。

还有,不要忘了在环境变量中PATH里将chrome的路径添加进去。

此时会打开一个浏览器页面,我们输入百度网址,我们把它当成一个已存在的浏览器。

现在,我们需要接管上面的浏览器。新建一个python文件,运行以下代码:

fromselenium import webdriverfromselenium.webdriver.chrome.options import Options

chrome_options=Options()

chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

chrome_driver= "chromedriver.exe"driver= webdriver.Chrome(chrome_driver, chrome_options=chrome_options)

print(driver.title)

driver.get("/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html")

会发现打印出了 “百度一下,你就知道” 的网页标题。这样我们就实现了对一个已打开的浏览器的控制。

更多需求可以自己在此基础上进行修改。

转自//08/11/how-to-connect-selenium-to-an-existing-browser-that-was-opened-manually/

翻译/lovealways

补充:由于测试上面代码时,我还没安装chromedriver,于是用以下代码安装:

pip install chromedriver

又从这里找到http://chromedriver./index.html chromedriver.exe(win32版本的) 放在当前脚本目录中(后来发现其实也不用下载,可以用之前C#代码测试时的chromedriver.exe)

然而,上面的代码证明,没能通过WebDriver反爬检测。

fromselenium import webdriverfromselenium.webdriver.chrome.options import Options

chrome_options=Options()

chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

chrome_driver= "chromedriver.exe"driver= webdriver.Chrome(chrome_driver, chrome_options=chrome_options)

script= '''Object.defineProperty(navigator, 'webdriver', {get: () =>undefined

})'''driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script})

print(driver.title)

driver.get("/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html")

哈哈,通过检测!

python接管已经打开ie浏览器_使用selenium控制(接管)已打开的浏览器(chrome) 并通过WebDriver值检测...

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。