C++
1<windows.h> 2#include <tchar.h> 3 4 5#include <atlbase.h> // CComQIPtr<_T> を使うのに必要 6#include <mshtml.h> // IHTMLDocument2 を使うのに必要 7#include <cstdio> 8#include <stdio.h> 9#include <string.h> 10#include <cstringt.h> 11#include <string> 12#include <iostream> 13#include <vector> 14#include <atlstr.h> 15#include <wchar.h> 16#include <stdlib.h> 17#include <stdio.h> 18#include <algorithm> 19 20 21#import <mshtml.tlb> 22using namespace std; 23 24 25#import <shdocvw.dll> 26#import <mshtml.tlb> 27 28#import "libid:EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B" no_namespace named_guids 29 30 31 32string Conv(CComBSTR); 33 34 35int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 36 PSTR szCmdLine, int iCmdShow) 37{ 38 HRESULT hr = ::CoInitialize(NULL); //COMを使うときのお約束 39 if (FAILED(hr)) { 40 return -1; 41 } 42 43 44 IWebBrowser2* pIE; 45 hr = CoCreateInstance( 46 CLSID_InternetExplorer, // InternetExplorer 47 NULL, 48 CLSCTX_LOCAL_SERVER, // 同じマシン・別プロセスでロード 49 IID_IWebBrowser2, 50 (VOID**)&pIE 51 ); 52 if (FAILED(hr)) { 53 printf("CoCreateInstance 失敗\n"); 54 exit(1); 55 } 56 57 // Visible にする 58 VARIANT_BOOL pBool = VARIANT_TRUE; 59 hr = pIE->put_Visible(pBool); 60 61 62 if (FAILED(hr)) { 63 printf("putVisible 失敗\n"); 64 exit(1); 65 } 66 // ブラウズする 67 68 69 hr = pIE->Navigate("https://www.yahoo.co.jp"); 70 71 72 while (pIE->Busy == VARIANT_TRUE || 73 pIE->ReadyState != READYSTATE_COMPLETE) 74 ::Sleep(100); 75 76 77 MSHTML::IHTMLDocument2Ptr pDoc = pIE->GetDocument(); 78 MSHTML::IHTMLDocument3Ptr pDoc1 = pDoc; 79 80 MSHTML::IHTMLElementCollectionPtr Data = pDoc1->getElementsByTagName("h1"); 81 MSHTML::IHTMLDocument3Ptr child = Data->item(0); 82 MSHTML::IHTMLElementCollectionPtr child2 = Data->item(0); 83 child->getElementsByTagName("a"); 84 long len; 85 child2->get_length(&len); 86 CComBSTR txt; 87 string Txt; 88 for (long i = 0; i < len; i++) { 89 MSHTML::IHTMLElementPtr msg = child2->item(i); 90 91 msg->get_innerHTML(&txt); 92 Txt = Conv(txt); 93 94 MessageBox(NULL, Txt.c_str(), "", MB_OK); 95 } 96 97 SysFreeString(txt); 98 99 100 pDoc->close(); 101 pDoc.Release(); 102 103 pIE->Quit(); 104 105 pIE->Release(); 106 107 108 ::CoUninitialize(); 109 MessageBox(NULL, "終了します", "Yahoo", MB_OK); 110 111 exit(0); 112 113} 114 115string Conv(CComBSTR tmp) { 116 string st = ""; 117 if (tmp.Length() <= 32767 && tmp.Length() > 0) { 118 LPCWSTR _lpw = tmp; 119 SysFreeString(tmp); 120 int _convert = 0; 121 _convert = (lstrlenW(_lpw) + 1) * 2; 122 123 //LPTSTR szString = _alloca(_convert); 124 LPTSTR szString = new char[_convert]; 125 126 127 AtlW2AHelper((LPSTR)szString, _lpw, _convert); 128 st = szString; 129 delete[] szString; 130 131 } 132 133 return st; 134} 135 136
h1タグの 子孫要素の aタグを順にアクセスしたいのですが (仮に <h1>と<a>タグにしている)
上手くいきません
ご教授 下さい
よろしく お願い致します
実際のhtmlを提示された方が回答が得やすくなります。
あなたの回答
tips
プレビュー