VBA:打开网站时出错

时间:2018-05-01 10:20:34

标签: vba hyperlink explorer basic

我缩短了代码以提高可见性:

Sub open_explorer()

    'Open Website 1
    Set IE = CreateObject("InternetExplorer.Application")

    IE.navigate ("https://www.google.ch/search?newwindow=0&q=Dodecan+Sigma-Aldrich")
    IE.Visible = True

    i = 0
    Do
        Wait
        i = i + 1
    Loop Until IE.ReadyState = 4 Or i > 10

    Set dom = IE.document
    Debug.Print (dom)
    Debug.Print (dom.anchors.Length)

    'Open Website 2
    Set IE = CreateObject("InternetExplorer.Application")

    IE.navigate ("https://www.sigmaaldrich.com/catalog/product/sial/457116?lang=en&region=US")
    IE.Visible = True

    i = 0
    Do
        Wait
        i = i + 1
    Loop Until IE.ReadyState = 4 Or i > 10

    Set dom = IE.document
    Debug.Print (dom)
    Debug.Print (dom.anchors.Length)

End Sub

Sub Wait()
    Application.Wait (Now + TimeValue("0:00:01"))
End Sub

正如您所见,Sub open_explorer打开了两个网站并尝试读取其DOM。虽然代码完全适用于第一个网站,但它不适用于第二个网站,尽管代码是相同的。任何想法为什么它不适用于第二个网站?

Error-Message

2 个答案:

答案 0 :(得分:0)

我认为至少将Option Explicit放在所有模块的顶部。然后在此代码中声明所有变量及其类型。以下适用于我。

注意:

如果浏览器出于安全原因阻止了同一来源的请求。您需要为跨域请求执行不同的操作。有关此问题的更多信息Using CORS 2

<强>代码:

Option Explicit

Sub open_explorer()

    Dim Ie As Object
    'Open Website 1
    Set Ie = CreateObject("InternetExplorer.Application")

    Ie.navigate ("https://www.google.ch/search?newwindow=0&q=Dodecan+Sigma-Aldrich")
    Ie.Visible = True

    Dim i As Long
    i = 0
    Do
        Wait
        i = i + 1
    Loop Until Ie.ReadyState = 4 Or i > 10
    Dim dom As Object
    Set dom = Ie.document
    Debug.Print (dom)
    Debug.Print (dom.anchors.Length)

    'Open Website 2
    Set Ie = CreateObject("InternetExplorer.Application")

    Ie.navigate ("https://www.sigmaaldrich.com/catalog/product/sial/457116?lang=en&region=US")
    Ie.Visible = True

    i = 0
    Do
        Wait
        i = i + 1
    Loop Until Ie.ReadyState = 4 Or i > 10

    Set dom = Ie.document
    Debug.Print (dom)
    Debug.Print (dom.anchors.Length)

End Sub

Sub Wait()
    Application.Wait (Now + TimeValue("0:00:01"))
End Sub

<强>结果:

Result

<强>参考文献:

  1. What do Option Strict and Option Explicit do?
  2. Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?

答案 1 :(得分:0)

我不知道为什么它适合你。我更正了“Option Explicit”标题,但这并没有解决CORS-Bug。

但是,我为我的服务器编写了一个小的PHP剪辑来加载URL:

<?php

$link = urldecode( $_GET['link'] );

$file = file_get_contents( $link );

echo $file;

现在间接加载链接非常有效。