seleniium执行js 发送get请求 解决跨域问题

这边需要使用selenium 执行一段js代码 发送get请求,现在就是无法解决跨域问题 如何解决


    //增加callback回调函数,异步TB无法return得到ajax的返回,除非同步请求
    function TB(url,callback) {
        var httpRequest = new XMLHttpRequest();//第一步:建立所需的对象
        httpRequest.open('GET', url, true);//第二步:打开连接  将请求参数写在url中  ps:"./Ptest.php?name=test&nameone=testone"
        httpRequest.send();//第三步:发送请求  将请求参数写在URL中
        /**
         * 获取数据后的处理程序
         */
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var json = httpRequest.responseText;//获取到json字符串,还需解析
                console.log(json);
                //return json
                callback(json);///这样给外部传递数据,return无意义,
            }
        };
        //这里return ajax的返回值也无效,因为ajax异步执行,为执行里面的回调就已经执行这句了,所以是得不到ajax返回值的
    }

    url = 'https://www.baidu.com'
    //这样来条用
    TB(url, function (p) {

        //需要使用返回值的js代码全部放这里面
        console.log(p)


    });




  • 直接用调用selenium的语言的http类库直接请求不行吗?比如Python的 requests,这种不存在跨域的问题。

  • 或者直接打开ajax请求的网址,直接在这个网址上做ajax请求是同源的也不会出现跨域问题。

一定要用selenium可以试试下面的方法
While using ChromeDriver / Chrome combo to disable cors check you can use the --disable-web-security argument.

sameoriginpolicy
which is defined in content_switches.cc as:

// Don't enforce the same-origin policy. (Used by people testing their sites.)
const char kDisableWebSecurity[] = "disable-web-security";

Code samples:Windows:


ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-web-security"); // don't enforce the same-origin policy
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--user-data-dir=~/chromeTemp"); // applicable to windows os only
WebDriver driver = new ChromeDriver(options);
driver.get("https://google.com");

来源:

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632