【问题标题】:Cannot perform auto search on a specific website无法在特定网站上执行自动搜索
【发布时间】:2019-02-13 22:02:54
【问题描述】:

最近我正在学习使用 excel 宏在网站上进行搜索。我已经阅读了几个论坛主题,并想出了下面的代码。但是,当我到达该行时出现错误

SearchBox(0).Value = SearchString

我试图删除 (0) 但也出现了另一个错误。该代码在其他网站上运行良好。我应该如何改变它们以适应这个网站?

附:我也想知道点击搜索按钮的方法。

Sub Searchstockcode()

    Dim SearchString As String

    SearchString = "700"

    Set ie = CreateObject("InternetExplorer.Application")
    With ie

    ie.Visible = True
    End With

    ie.Navigate "http://www.hkexnews.hk/listedco/listconews/advancedsearch/search_active_main.aspx"

    While ie.ReadyState <> 4

    DoEvents

    Wend


    Dim SearchBox As Object

    Set SearchBox = ie.Document.GetElementsByName("ct100$txt_stock_code")

    SearchBox(0).Value = SearchString


    Dim SearchButton As Object

    Set SearchButton = ie.Document.GetElementsByName


End Sub

【问题讨论】:

  • 请与我们分享您收到的确切错误消息。此外,此宏还可以与哪些其他网站配合使用?这样我们就可以比较/对比他们的 html。

标签: excel vba web-scraping


【解决方案1】:

我不知道您的名称选择问题是否是由于元素具有两个名称属性,但这似乎是可能的。

您可以使用以下内容。

对于搜索框,我使用它的 id 来定位元素。这通常在文档上是唯一的,也是最快的选择器方法。

对于搜索按钮,我使用了

的 CSS 属性 + 值选择器
[src*='/image/search.gif']

这将通过其值定位元素的src 属性[]* 表示包含。选择器会查找在其值中包含 /image/search.gifsrc 属性。

你可以在这里观察属性:

Option Explicit
Sub Searchstockcode()

    Dim SearchString As String, SearchBox As Object, SearchButton As Object, ie As Object

    SearchString = "700"

    Set ie = CreateObject("InternetExplorer.Application")

    ie.Visible = True

    ie.navigate "http://www.hkexnews.hk/listedco/listconews/advancedsearch/search_active_main.aspx"

    While ie.Busy Or ie.readyState < 4: DoEvents: Wend

    Set SearchBox = ie.document.getElementById("ctl00_txt_stock_code")
    SearchBox.Value = SearchString

    Set SearchButton = ie.document.querySelector("[src*='/image/search.gif']")
    SearchButton.Click

    While ie.Busy Or ie.readyState < 4: DoEvents: Wend

    Stop '<==Delete me
    'other code
    ie.Quit
End Sub

【讨论】:

  • 感谢 Qharr!它工作得很好!我认为我出错的原因是因为我搞砸了“l”和“1”哈哈!我还有一个关于下一步的问题:我总是想点击点击搜索按钮后出现的第一个链接。我认为这段代码应该可以工作:'Set TargetFile = i.e.document.getElementById("ctl00_gvMain_ctl02_hlTitle") TargetFile.Click' 但之后我不知道如何保存或打开文件。我的目的是打开文件并提取某些数据。提前非常感谢您!
  • 假设什么代码可以工作?发布您正在尝试的问题并在此处留下链接,我会看看。确保说明应该发生的事情和正在发生的事情。
  • 设置 TargetFile = i.e.document.getElementById("ctl00_gvMain_ctl02_hlTitle") TargetFile.Click
  • 发布一个问题,因为在此处的 cmets 中调试更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多