Excel VBA(基于Selenium)代码补全:实现Chrome网页性别下拉框选择
Got it, let's fill in that missing logic for selecting the male gender option when your sheet's cell value is "M". Based on the HTML dropdown structure you shared, there are two straightforward ways to implement this:
Method 1: Directly Target the Option Element
You can use an XPath selector to find the <option> tag with value="M" and click it directly. This is simple and works well for static dropdowns:
If Sheet1.Cells(row, 6) = "M" Then ' Directly click the Male option by targeting its value attribute bot.FindElementByXPath("//select[@id='gender']/option[@value='M']").Click End If
Method 2: Use the SelectElement Class (More Robust)
For a more standardized approach to handling dropdowns, you can use Selenium's SelectElement class. This is especially useful if you might need to handle other selection scenarios (like choosing by text or index) later:
If Sheet1.Cells(row, 6) = "M" Then ' Initialize a SelectElement for the gender dropdown Dim genderDropdown As SelectElement Set genderDropdown = New SelectElement Set genderDropdown = bot.FindElementById("gender") ' Select the Male option by its value attribute genderDropdown.SelectByValue "M" ' Alternatively, you could select by visible text: ' genderDropdown.SelectByText "Male" End If
Full Updated Code Snippet
Here's how your complete subroutine will look with Method 1 (you can swap in Method 2 if preferred):
Sub google_search() Dim row As Integer row = 2 Dim bot As WebDriver Set bot = New WebDriver bot.Start "chrome" bot.Get "https://abcd.com/" bot.FindElementbyName("patient_name").SendKeys "Value" bot.FindElementbyName("patient_id").SendKeys "Value" If Sheet1.Cells(row, 4) = "Years" Then bot.FindElementById("age_year").Click bot.FindElementbyName("age").SendKeys "Value" ElseIf Sheet1.Cells(row, 4) = "Months" Then bot.FindElementById("age_month").Click bot.FindElementbyName("age").SendKeys "Value" Else End If If Sheet1.Cells(row, 6) = "M" Then ' Directly click the Male option bot.FindElementByXPath("//select[@id='gender']/option[@value='M']").Click End If Stop End Sub
Both methods will reliably select the "Male" option when your sheet's cell (row,6) contains "M". The SelectElement approach is more flexible if you plan to expand the gender selection logic later (e.g., handling "F" or "T" values).
内容的提问来源于stack exchange,提问作者Joseph John

