峰大爷 2022-06-09 11:57 采纳率: 83.9%
浏览 91
已结题

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)


    });




  • 写回答

2条回答 默认 最新

  • CSDN专家-showbo 2022-06-09 12:04
    关注
    • 直接用调用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");
    
    

    来源:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月18日
  • 已采纳回答 6月10日
  • 创建了问题 6月9日

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装