使用VBA的下拉菜单

时间:2019-06-19 17:30:19

标签: excel vba web-scraping dropdown queryselector

我需要使用VBA从下拉菜单中选择特定选项。我该怎么办?

https://clinicaltrials.gov/ct2/results?cond=&term=Medpace&cntry=&state=&city=&dist= 链接到我们试图从

提取的网页

IE.document.getElementsByName(“ down_count”)。click我尝试过的代码

Full Module:
Private Sub Workbook_Open()
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.application")
    With IE
        .Visible = True
        .Navigate ("https://clinicaltrials.gov/ct2/results?cond=&term=Medpace&cntry=&state=&city=&dist=")
        While .Busy Or .readyState <> 4: DoEvents: Wend

    End With

    With IE.document
    IE.Refresh
        Set div = IE.document.getElementById("save-list-link")
        div.FireEvent "onclick"
    ' Application.SendKeys "{TAB}", True
    ' Application.SendKeys "{TAB}", True
    ' Application.SendKeys "{SPACE}", True
    ' Application.SendKeys "{DOWN}", True
    ' Application.SendKeys "{ENTER}", True
    ' Application.SendKeys "{TAB}", True
    ' Application.SendKeys "{TAB}", True
    ' Application.SendKeys "{SPACE}", True
    ' Application.SendKeys "{DOWN}", True
    ' Application.SendKeys "{DOWN}", True
    ' Application.SendKeys "{DOWN}", True
    ' Application.SendKeys "{ENTER}", True
    IE.document.getElementsByName("down_count").click
    ' For Each elt In IE.document.getElementById("number-of-studies")
        ' If InStr(elt.innerText, "Found") > 0 Then elt.click: Exit For
    ' Next elt

    Set div4 = IE.document.getElementById("submit-download-list")
    div4.click
    End With
End Sub

想要将“研究数量”转到“找到的全部”(此数字会更改) 并选择文件格式为CSV

1 个答案:

答案 0 :(得分:1)

下面显示了如何下载

Option Explicit

'VBE > Tools > References: Microsoft Internet Controls
Public Sub GetData()
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate2 "https://clinicaltrials.gov/ct2/results?cond=&term=Medpace&cntry=&state=&city=&dist="

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

        With .document
            .querySelector("#save-list-link").Click
            .querySelector("#number-of-studies option:last-child").Selected = True 'select last option from that dropdown
            '.querySelector("#number-of-studies").selectedIndex = 1  ''selects 2nd option
            .querySelector("[value=csv]").Selected = True 'select csv with attribute = value css selector

            .querySelector("#submit-download-list").Click
        End With
        Application.Wait Now + TimeSerial(0, 0, 10)
        Application.SendKeys "%+O", True
        Application.Wait Now + TimeSerial(0, 0, 10)
        .Quit
    End With
End Sub