【发布时间】:2021-07-11 10:41:11
【问题描述】:
我正在尝试使用来自该网站的信息更新我的物种数据库:https://www.afcd.gov.hk/english/conservation/hkbiodiversity/database/search.php
我有一个 xlsm,其中包含 A 列中的物种列表,并在网站的搜索引擎中搜索它们中的每一个,这会导致一个页面显示指向该特定物种的另一个页面的链接。每个物种都由一个唯一的 ID 标识,这就是我想要的信息。
例如如果我在搜索框“科学名称”中输入“Mnais mneme”,则会出现一个页面,该页面显示一个包含该物种的表格,并附有其名称的链接 (https://www.afcd.gov.hk/english/conservation/hkbiodiversity/database/popup_record.php?id=781&lang=en)。 “781”是物种 ID。
我想将此链接复制到我的 xlsm 的 B 列中并在 Excel 中提取 ID:
Sub SearchBot()
'dimension (declare or set aside memory for) our variables
Dim objIE As InternetExplorer 'special object variable representing the IE browser
'link will be the <a> carrying the href with the species id
Dim link As HTMLAnchorElement
'define y as interger counter
Dim y As Integer
'initiating a new instance of Internet Explorer and assigning it to objIE
Set objIE = New InternetExplorer
'make IE browser visible (False would allow IE to run in the background)
objIE.Visible = True
'navigate IE to this web page
objIE.navigate "https://www.afcd.gov.hk/english/conservation/hkbiodiversity/database/search.php"
'wait here for a few seconds while the browser is busy
Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
objIE.document.getElementById("s1").Click
'in the search box put cell "A2" value
objIE.document.all.Item("scientific_name").Value = Sheets("Sheet1").Range("A2").Value
'click the 'Search' button
objIE.document.getElementsByClassName("btn_3")(1).Click
'wait again for the browser
Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
'select the species name link
Set link = objIE.document.getElementsByTagName("td")(4).getElementsByTagName ("a")(0)
y = 2
'print the link to column B in Sheet1
Sheets("Sheet1").Range("B" & y).Value = link.href
End Sub
调试展示
运行时错误 91
在最后一行停止时:
Sheets("Sheet1").Range("B" & y).Value = link.href
将链接设置为 HTMLAnchorElement 是否有问题?我尝试将其设置为 Object 但仍然出现错误。
【问题讨论】:
-
我从我的机器上进行了快速比较...我在页面上找不到 ("td")(4) 元素。我找不到 ("td")(3) 或 ("td")(2),但是
Set link = objIE.document.getElementsByTagName("td")(1).getElementsByTagName("a")(0)返回值并且没有出错。我认为您需要再次检查源页面元素。 -
感谢您的回复!初始搜索后可以在页面上找到元素:afcd.gov.hk/english/conservation/hkbiodiversity/database/… 链接在表格第 5 格的物种名称中,源代码为您的代码无需修改即可为我工作。你确定
Sheet1是活动表吗?尝试在y = 2之后添加Sheets("Sheet1").Activate和Sheets("Sheet1").Select。我也喜欢并支持@Ryan Wildry 的回答。效果很好。我仍然无法摆脱添加了两行的错误消息....我不知道为什么...但是非常感谢您添加该建议!
标签: html excel vba web-scraping runtime-error