首先贴出一下选择框的网页元素代码
- <div class="select"><select id="cond_PSPT_TYPE" name="cond_PSPT_TYPE" disabled="disabled" class="e_select" desc="选择框" type="text">
- <option value="">-----默认选择-----</option>
- <option value="0">选项0</option>
- <option value="1">选项0</option>
- </select></div> </div></div>
先通过IHTMLSelectElement接口获得所选item的value,程序中是strValue;
再通过IHTMLOptionElement接口遍历判断value同strValue的下拉选项元素的文本信息。
同一个网页框架中有多个选择框,且出现2个value值相同的下拉选项元素时,此法不可行。
- CString GetText()
- {
- CString strValue;
- CString strText;
- HRESULT hr;
- IDispatch *pDisp;
- pDisp = m_webBrowser.get_Document(); // 获取webbrowser控件文档接口
- IHTMLDocument2* pDoc;
- hr = pDisp->QueryInterface( IID_IHTMLDocument2, (void**)&pDoc ); // 获取操作界面的文档接口
- IHTMLElementCollection* pColl = NULL;
- hr = pDoc->get_all( &pColl ); // 获取网页元素集合
- // ------------------------获取选择框的所选item的value-----------------------------------------
- VARIANT index;
- VARIANT varID;
- V_VT(&index) = VT_I4;
- V_I4(&index) = 0;
- CString IDSelect = "cond_PSPT_TYPE"; // IDSelect是选择框的网页元素ID
- varID = StringToVariant(IDSelect);
- hr = pColl->item(varID, index, &pDisp); // 获得选择框位置
- if ( (hr == S_OK) && (pDisp != NULL) )
- {
- IHTMLSelectElement * pSelect; // 获得选择框元素接口
- hr = pDisp->QueryInterface(IID_IHTMLSelectElement,(void **)&pSelect );
- if ( (hr == S_OK) && (pSelect != NULL) )
- {
- BSTR bstr = SysAllocString(L"");
- pSelect->get_value(&bstr); // 获取选择框所选item的value
- strValue = bstr;
- pSelect->Release();
- }
- pDisp->Release();
- }
- // ------------------------获取选择框的所选item的文本信息--------------------------------------
- long cntElement;
- hr = pColl->get_length(&cntElement); // 获取网页元素个数
- for(int i = 0; i < cntElement; i++)
- {
- IDispatch* pDisp2;
- V_I4(&index) = i;
- hr = pColl->item( index,index, &pDisp2 ); // 获取元素位置
- if ( (hr == S_OK) && (pDisp2 != NULL) )
- {
- IHTMLOptionElement* pOptElem; // 获取下拉选项元素接口
- hr = pDisp2->QueryInterface(IID_IHTMLOptionElement,(void **)&pOptElem);
- if ( (hr == S_OK) && (pOptElem != NULL) )
- {
- BSTR bstr = SysAllocString(L"");
- pOptElem->get_value(&bstr); // 获取下拉选项元素的value
- CString strTemp = "";
- strTemp = bstr;
- if(strTemp == strValue)
- {
- pOptElem->get_text(&bstr); // 获取下拉选项元素的文本信息
- strText = bstr;
- i = cntElement;
- }
- pOptElem->Release();
- }
- pDisp2->Release();
- }
- }
- pDoc->Release();
- pColl->Release();
- return strText;
- }