我曾经遇到过许多类似的问题,例如this和this,但是我的问题要简单得多。我想更改网络表单上的日期并使用POST请求获取数据
我有发出POST请求的代码:
Sub winpost()
Dim WebClient As WinHttp.WinHttpRequest
Set WebClient = New WinHttp.WinHttpRequest
Dim searchResult As HTMLTextElement: Dim searchTxt As String
Dim html As New HTMLDocument
Dim Payload As String
Payload = "ContentPlaceHolder1_ddlday=6"
With WebClient
.Open "POST", "http://pib.nic.in/AllRelease.aspx", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (Payload)
.waitForResponse
End With
html.body.innerHTML = WebClient.responseText
Set searchResult = html.querySelector(".search_box_result"): searchTxt = searchResult.innerText
Debug.Print searchTxt
End Sub
网站为this。该页面会在任何字段更改时发送发布请求。 在网络> Formdata部分下查看ChromeDevTools时,我看到以下内容:
ctl00$ContentPlaceHolder1$ddlday: 8
我已经在Payload字符串中尝试了各种版本,但始终返回同一页面(1月8日)。
答案 0 :(得分:1)
Internet Explorer
使用IE时,其语法与selenium basic(底部显示)略有不同,因为没有SelectByText选项。例如,您可以使用索引或attribute = value css选择器。这里的月份是最多12个索引,而不是月份名称
Option Explicit
Public Sub SetDates()
Dim ie As New InternetExplorer
With ie
.Visible = True
.Navigate2 "http://pib.nic.in/AllRelease.aspx"
While .Busy Or .readyState < 4: DoEvents: Wend
With .Document
.querySelector("#btnSave").Click
.querySelector("#ContentPlaceHolder1_ddlMonth [value='2']").Selected = True
.querySelector("#ContentPlaceHolder1_ddlYear [value='2018']").Selected = True
.querySelector("#ContentPlaceHolder1_ddlday [value='2']").Selected = True
End With
Stop '<==delete me later
.Quit
End With
End Sub
基本硒:
如果您沿selenium basic vba路线行驶,则可以执行以下操作。注意:安装硒后,您需要进入VBE>工具>引用>将引用添加到硒类型库。您还需要使用最新的Chrome,并将ChromeDriver和ChromeDriver文件夹放置在环境路径中,或者将chromedriver放置在包含硒可执行文件的文件夹中。
Option Explicit
Public Sub SetDates()
Dim d As WebDriver
Set d = New ChromeDriver
Const Url = "http://pib.nic.in/AllRelease.aspx"
With d
.Start "Chrome"
.get Url
.FindElementById("btnSave").Click
'date values
.FindElementById("ContentPlaceHolder1_ddlMonth").AsSelect.SelectByText "February"
.FindElementById("ContentPlaceHolder1_ddlYear").AsSelect.SelectByText "2018"
.FindElementById("ContentPlaceHolder1_ddlday").AsSelect.SelectByText "2"
Stop 'delete me later
.Quit
End With
End Sub