求助:使用Excel VBA自动化checkcosmetic.net时的选项列表选择问题
我来帮你搞定这个Excel VBA自动化查询化妆品保质期的问题!之前我自己做类似网站自动化的时候,也碰到过下拉选择卡壳的情况,主要看页面的下拉框是原生HTML控件还是自定义的,给你两种场景的解决方案:
解决方案:分两种情况处理下拉选择
情况1:页面用原生HTML <select>下拉框
如果品牌选择是原生的下拉控件(你可以按F12打开开发者工具,看元素标签是不是<select>),用下面的代码就能直接选中目标品牌:
Sub QueryCosmeticExpiry() Dim ie As Object Set ie = CreateObject("InternetExplorer.Application") ie.Visible = True ' 设为False可以后台运行 ie.Navigate "https://checkcosmetic.net" ' 等待页面完全加载 Do While ie.Busy Or ie.ReadyState <> 4 DoEvents Loop ' 选择品牌:Vaseline Dim brandSelect As Object Set brandSelect = ie.Document.getElementById("brandSelect") ' 替换为实际的select元素ID For Each opt In brandSelect.Options If Trim(opt.Text) = "Vaseline" Then opt.Selected = True Exit For End If Next opt ' 输入批号 ie.Document.getElementById("batchNumber").Value = "09076JU40" ' 替换为实际的批号输入框ID ' 点击查询按钮 ie.Document.getElementById("checkButton").Click ' 替换为实际的查询按钮ID ' 等待结果加载 Do While ie.Busy Or ie.ReadyState <> 4 DoEvents Loop ' 获取保质期结果并写入Excel Dim expiryResult As String expiryResult = ie.Document.getElementById("expiryDate").innerText ' 替换为实际的结果元素ID ThisWorkbook.Sheets("Sheet1").Range("A1").Value = "保质期:" & expiryResult ' 关闭浏览器 ie.Quit Set ie = Nothing End Sub
情况2:页面用自定义下拉菜单(非原生select)
很多网站会用自定义的下拉(比如点击按钮弹出选项列表,标签是<div>或<ul>),这时候需要模拟点击展开下拉,再点击目标选项:
Sub QueryCosmeticExpiry_CustomDropdown() Dim ie As Object Set ie = CreateObject("InternetExplorer.Application") ie.Visible = True ie.Navigate "https://checkcosmetic.net" Do While ie.Busy Or ie.ReadyState <> 4 DoEvents Loop ' 点击下拉按钮展开品牌列表 ie.Document.querySelector(".brand-dropdown-trigger").Click ' 替换为实际的下拉按钮class/选择器 Application.Wait Now + TimeValue("00:00:01") ' 等待下拉列表展开 ' 找到并点击Vaseline选项 Dim brandOption As Object For Each brandOption In ie.Document.querySelectorAll(".dropdown-item") ' 替换为实际的选项元素选择器 If InStr(brandOption.innerText, "Vaseline") > 0 Then brandOption.Click Exit For End If Next brandOption ' 输入批号 ie.Document.getElementById("batchNumber").Value = "09076JU40" ' 点击查询 ie.Document.getElementById("checkButton").Click Do While ie.Busy Or ie.ReadyState <> 4 DoEvents Loop ' 获取结果写入Excel Dim expiryResult As String expiryResult = ie.Document.querySelector(".expiry-result").innerText ' 替换为实际的结果元素选择器 ThisWorkbook.Sheets("Sheet1").Range("A1").Value = "保质期:" & expiryResult ie.Quit Set ie = Nothing End Sub
关键注意事项
- 确认元素标识:一定要用开发者工具(F12)查看网站的实际元素ID/class,替换代码里的占位符(比如
brandSelect、batchNumber这些),因为网站可能会更新结构。 - 优化等待逻辑:如果页面加载慢,单纯的
ReadyState判断可能不够,可以改成循环检查元素是否存在:' 等待品牌下拉元素出现 Do While ie.Document.getElementById("brandSelect") Is Nothing DoEvents Loop - 反爬应对:如果频繁操作被网站拦截,在每步操作之间加1-2秒延迟,比如
Application.Wait Now + TimeValue("00:00:01"),模拟人类操作节奏。
内容的提问来源于stack exchange,提问作者rens
相关产品推荐
相关产品推荐

