<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; VBS: Парсинг HTML через MSXML]]></title>
	<link rel="self" href="http://forum.script-coding.com/extern.php?action=feed&amp;tid=8652&amp;type=atom" />
	<updated>2015-03-05T20:10:54Z</updated>
	<generator>PunBB</generator>
	<id>http://forum.script-coding.com/viewtopic.php?id=8652</id>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=92312#p92312" />
			<content type="html"><![CDATA[<p>В том, что теги есть одинарные и двойные. В XML имеется регистрозависимость, в HTML-нодах - нет. Атрибуты то с кавычками, то без. Теги, в которых имеются данные надо оформлять в CDATA и т.п.</p>]]></content>
			<author>
				<name><![CDATA[JSmаn]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=24434</uri>
			</author>
			<updated>2015-03-05T20:10:54Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=92312#p92312</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=92283#p92283" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Xameleon пишет:</cite><blockquote><p>... <strong>Нужно распарсить&nbsp; HTML документ средствами MSXML</strong>. Да, знаю криво и коряво и вообще так делать нельзя, ...</p></blockquote></div><p><strong>Xameleon</strong>, поясните, пожалуйста, в чем заключаются противопоказания?</p>]]></content>
			<author>
				<name><![CDATA[omegastripes]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=29228</uri>
			</author>
			<updated>2015-03-05T10:48:31Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=92283#p92283</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=77943#p77943" />
			<content type="html"><![CDATA[<p><strong>dab00</strong>, благодарю, но решение с <strong>htmlfile</strong> меня пока что больше устраивает. ) Экономичнее.</p>]]></content>
			<author>
				<name><![CDATA[Xameleon]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=8836</uri>
			</author>
			<updated>2013-12-09T13:15:27Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=77943#p77943</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=77890#p77890" />
			<content type="html"><![CDATA[<p><strong>Xameleon</strong>, если тема еще актуальна - <a href="https://github.com/MatthewMueller/cheerio">вот</a> неплохой модуль для Node.js, <a href="http://www.daspot.ru/2013/12/server-side-jquery-html.html">здесь</a> рассказал как пользоваться. <br />Конечно не &quot;средствами MSXML&quot;, но тем не менее.</p>]]></content>
			<author>
				<name><![CDATA[dab00]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=27085</uri>
			</author>
			<updated>2013-12-07T12:23:21Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=77890#p77890</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75419#p75419" />
			<content type="html"><![CDATA[<p><strong>shiz</strong> без проблем.</p><p>Первое с чем столкнулся уже давно, это то что <strong>htmlfile</strong> в ASP создаётся не с первого раза. Скрипт выдаёт ошибку с кодом <strong>8000ffff</strong> без вменяемого описания. Для обхода этого &quot;косяка&quot; сделал цикл, который проверяет создание объекта. Проверять на Err.Number = 0 не получилось, т.к хоть со второго раза объект всё же создаётся, но ошибка при этом всё равно происходит. Поэтому оставил проверку на <strong>isObject</strong>.</p><div class="codebox"><pre><code>
    On Error Resume Next
    For i=1 to 10
        Set document = CreateObject(&quot;htmlfile&quot;)
        if isObject(document) Then 
            ....
            Exit Function
        End if
    Next
</code></pre></div><p>Следующей (недавней ошибкой, а вернее их массой) стало то, что перестал автоматически создаваться <strong>HTMLBody</strong> у <strong>document</strong> после выполнения кода<br /></p><div class="codebox"><pre><code>
document.open
document.close
</code></pre></div><p>К этому добавились ещё ошибки при выполнении <strong>insertAdjacentHTML</strong> и даже <strong>document.write</strong>, что крайне меня расстроило. Точных подробностей и описаний ошибок не помню, но по виду они напоминали всё туже неопознанную ошибку.</p><p>Решил попробовать создавать <strong>HTMLBody</strong> искусствено и заполнить его нужным мне содержимым.</p><div class="codebox"><pre><code>
With document
    .open
    .close
    .appendChild document.createElement(&quot;body&quot;)
    .body.innerHTML = HTMLCode
End With
</code></pre></div><p>И о чудо, &quot;рухлядь&quot; всё таки завелась с третьего раза !</p><p>В итоге пока что пользуюсь кодом &quot;на костылях&quot;:</p><div class="codebox"><pre><code>
&lt;%@Language=VBScript CodePage=1251 %&gt;
&lt;%
Option Explicit

Dim HTMLCode, document

HTMLCode = &quot;&lt;html&gt;&lt;body&gt;TEST&lt;/body&gt;&lt;/html&gt;&quot;

Set document = createHTMLDocument(HTMLCode)

Response.Write document.body.outerHTML

Function createHTMLDocument(HTMLCode)
    Dim document, i
    On Error Resume Next
    For i=1 to 10
        Set document = CreateObject(&quot;htmlfile&quot;)
        if isObject(document) Then 
            On Error Goto 0
            With document
                .open
                .close
                .appendChild document.createElement(&quot;body&quot;)
                .body.innerHTML = HTMLCode
            End With
            Set createHTMLDocument = document
            Exit Function
        End if
    Next
    On Error Goto 0
    Err.Raise vbObjectError,&quot;createHTMLDocument&quot;,&quot;Can&#039;t create html document&quot;
End Function

%&gt;
</code></pre></div><p>P.S В принципе все эти костыли [вроде бы] убираются, если дать htmlfile-у повышенные права в службе компонентов, но как-то не доверяю я ему на столько, да и зачастую на бесплатных хостах кидаю скрипты, а там с правами жёстко - что дали, тем и пользуйся.</p>]]></content>
			<author>
				<name><![CDATA[Xameleon]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=8836</uri>
			</author>
			<updated>2013-09-17T09:56:40Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75419#p75419</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75412#p75412" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Xameleon пишет:</cite><blockquote><p>с последним апдейтом мелкомягких, <strong>htmlfile</strong> перестал парсить HTML код в ASP. Не буду вдаваться в подробности.</p></blockquote></div><div class="quotebox"><cite>Xameleon пишет:</cite><blockquote><p><strong>htmlfile</strong> тоже победил. Нашёл уловку обходящую ошибку.</p></blockquote></div><p>Было бы очень интерсно познакомиться со встретившимся затруднением и вашим решением!</p>]]></content>
			<author>
				<name><![CDATA[shiz]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=26249</uri>
			</author>
			<updated>2013-09-16T20:39:04Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75412#p75412</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75398#p75398" />
			<content type="html"><![CDATA[<p><strong>omegastripes</strong>, благодарю за код. ) Погонял, пооптимизил использовал для других целей. <strong>htmlfile</strong> тоже победил. Нашёл уловку обходящую ошибку.</p>]]></content>
			<author>
				<name><![CDATA[Xameleon]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=8836</uri>
			</author>
			<updated>2013-09-16T07:22:41Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75398#p75398</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75332#p75332" />
			<content type="html"><![CDATA[<p><strong>omegastripes</strong> &amp; <strong>Serge Yolkin</strong>, благодарю, сейчас поизучаю. )</p>]]></content>
			<author>
				<name><![CDATA[Xameleon]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=8836</uri>
			</author>
			<updated>2013-09-11T12:40:21Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75332#p75332</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75331#p75331" />
			<content type="html"><![CDATA[<p>[off]<br />В 9-м году пара юношей тянула деньги с моего приятеля за создание его сайта. Так началось моё увлечение веб технологиями и, в частности, скриптингом. Привожу подчищенный перл из того творения.<br />[/off]</p><div class="codebox"><pre><code>&lt;div id=&quot;pForm&quot; style=&quot;border:dotted 1px;width:19em;&quot;&gt;
  &lt;table style=&quot;background-color:yellow;&quot;&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;img &gt;
      &lt;th&gt;Таблица 1
        &lt;table style=&quot;border:solid 1px;&quot;&gt;
          &lt;tr&gt;
            &lt;td&gt;1.2.1.1
            &lt;th&gt;1.2.1.2
            &lt;td&gt;1.2.1.3
          &lt;tr&gt;
            &lt;th&gt;1.2.2.1
            &lt;td&gt;1.2.2.2
            &lt;th&gt;1.2.2.3
        &lt;/table&gt;
      &lt;th&gt;&lt;a href=&quot;&quot;&gt;Ссылка
    &lt;tr&gt;
      &lt;td&gt;&lt;img &gt;
      &lt;th&gt;
        &lt;table style=&quot;border:solid 1px;&quot;&gt;
          &lt;tr&gt;
            &lt;td&gt;&lt;button id=&quot;b1&quot;&gt;2.2.1.1
            &lt;th&gt;&lt;button id=&quot;b2&quot;&gt;2.2.1.2
            &lt;td&gt;&lt;button id=&quot;b3&quot;&gt;2.2.1.3
  &lt;/table&gt;
  &lt;/table&gt;
  &lt;/table&gt;
  &lt;p&gt;Подвал формы
&lt;/div&gt;
&lt;p&gt;Продолжение документа
</code></pre></div><p>Подправил немного под ИЕ, чтобы не приводить стиль из того шедевра с кроссбраузерными хаками. Ну и отформатировал, как смог. Я не представляю ПРОСТОГО способа программно определить, куда ставить закрывающие теги. А ИЕ понимает... Сохраните это под именем kosyak.htm и откройте в ИЕ.</p>]]></content>
			<author>
				<name><![CDATA[Serge Yolkin]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=27503</uri>
			</author>
			<updated>2013-09-11T12:10:28Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75331#p75331</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75326#p75326" />
			<content type="html"><![CDATA[<div class="quotebox"><cite>Xameleon пишет:</cite><blockquote><p>к сожалению <span class="bbu"><strong>от ошибки с незакрытыми тегами пока не получается &quot;отучить&quot;</strong></span>. А такие тэги часто встречаются - &lt;base&gt; &lt;input&gt; &lt;img&gt;</p></blockquote></div><p>Допиливание HTML под MSXML с помощью наспех сооруженной функции msxmlcure(), которую я привожу ниже, позволило обойти ошибку незакрытых тегов. Но если провести тесты на текстах реальных страниц, то начинают валиться самые разнообразнейшие ошибки. Что-то подсказывает мне, что незакрытые теги будут далеко не единственной проблемой.<br /></p><div class="codebox"><pre><code>Option Explicit
Dim DOMDocument, raw, cured
raw = &quot;&lt;!DOCTYPE HTML PUBLIC &quot;&quot;-//W3C//DTD HTML 4.01//EN&quot;&quot; &quot;&quot;http://www.w3.org/TR/html4/strict.dtd&quot;&quot;&gt;&lt;/p&gt;&lt;html&gt;&lt;base&gt;abc&lt;/div&gt;&lt;head&gt;&lt;/head&gt;&lt;!-- комментарий --&gt;&lt;body&gt;&lt;div&gt;content&lt;img src=&#039;http://yandex.st/www/1.675/yaru/i/logo.png&#039;&gt;&lt;/body&gt;&lt;/html&gt;&quot;

&#039; убрать пробелы в тегах после &lt;
with createobject(&quot;VBScript.RegExp&quot;)
    .global = true
    .pattern = &quot;&lt;\s+&quot;
    raw = .replace(raw, &quot;&lt;&quot;)
end with

cured = msxmlcure(raw)

msgbox raw &amp; vbcrlf  &amp; vbcrlf &amp; cured, 64, &quot;RESULT&quot;

Set DOMDocument = HTMLToDOMDocument(cured)

msgbox &quot;DOMDocument elts found: &quot; &amp; DOMDocument.getelementsbytagname(&quot;*&quot;).length

Function HTMLtoDOMDocument(htmlcode)
    Dim DOMDocument: Set DOMDocument = CreateObject(&quot;Msxml2.FreeThreadedDOMDocument.6.0&quot;)
    With DOMDocument
        .validateOnParse = False
        .resolveExternals = False
        .PreserveWhiteSpace = True
        .setProperty &quot;ProhibitDTD&quot;,False
        .setProperty &quot;SelectionLanguage&quot;, &quot;XPath&quot;
        .loadXml htmlcode
        if .parseError &lt;&gt; 0 Then
            With .parseError
                Err.Raise .errorCode, &quot;HTMLtoDOMDocument&quot;, .reason &amp; vbCrlf &amp; &quot;line: &quot; &amp; .line &amp; vbCrlf &amp; &quot;linePos:&quot; &amp; .linePos &amp; vbCrlf &amp; &quot;srcText: &quot; &amp; .srcText
            End With
        End if
    End With
    Set HTMLtoDOMDocument = DOMDocument
End Function

function msxmlcure(text)
    dim openmatches, closematches, opentag, closetag, tagname, pref, inner, tail
    with createobject(&quot;VBScript.RegExp&quot;)
        .pattern = &quot;&lt;[^&gt;]+&gt;&quot; &#039; открывающий тег
        set openmatches = .execute(text)
        if openmatches.count &gt; 0 then &#039; найден тег
            set opentag = openmatches.item(0)
            if mid(opentag.value, 2, 1) = &quot;/&quot; then &#039; это закрывающий тег
                msxmlcure = msxmlcure(.replace(text, &quot;&quot;)) &#039; удалить
            else &#039; это открывающий тег
                pref = left(text, opentag.firstindex)
                if left(opentag.value, 2) = &quot;&lt;!&quot; then &#039; это тег &lt;! ...
                    inner = mid(text, opentag.firstindex + opentag.length + 1)
                    msxmlcure = msxmlcure(pref) &amp; opentag.value &amp; msxmlcure(inner)
                else
                    with createobject(&quot;VBScript.RegExp&quot;)
                        .pattern = &quot;\w+&quot; &#039; имя тега
                        tagname = .execute(opentag.value).item(0).value
                        .pattern = &quot;&lt;/&quot; &amp; tagname &amp; &quot;&gt;&quot; &#039; закрывающий тег
                        set closematches = .execute(text)
                    end with
                    if closematches.count &gt; 0 then &#039; найден соответствующий закрывающий тег
                        set closetag = closematches.item(0)
                        inner = mid(text, opentag.firstindex + opentag.length + 1, closetag.firstindex - opentag.firstindex - opentag.length)
                        tail = mid(text, closetag.firstindex + closetag.length + 1)
                        msxmlcure = msxmlcure(pref) &amp; opentag.value &amp; msxmlcure(inner) &amp; closetag.value &amp; msxmlcure(tail)
                    else &#039; соответствующий закрывающий тег отсутствует
                        inner = mid(text, opentag.firstindex + opentag.length + 1)
                        msxmlcure = msxmlcure(pref) &amp; left(opentag.value, opentag.length - 1) &amp; &quot; /&gt;&quot; &amp; msxmlcure(inner)
                    end if
                end if
            end if
        else &#039; тег не найден
            msxmlcure = text
        end if
    end with
end  function</code></pre></div>]]></content>
			<author>
				<name><![CDATA[omegastripes]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=29228</uri>
			</author>
			<updated>2013-09-10T22:53:35Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75326#p75326</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75313#p75313" />
			<content type="html"><![CDATA[<p><strong>Serge Yolkin</strong>, благодарю за предложенный вариант, но к сожалению использовать IE в ASP (Active Server Pages) крайне накладно, ресурсоёмко и ненадёжно. 1) Запуск IE под ASP требует выдачи повышенных прав для зависимых компонентов. 2) В случае падения ASP - загруженный экземпляр IE будет торчать в памяти 3) В теле страницы могут быть скрипты которые IE начнёт исполнять. Может &quot;тупануть&quot; на alert-е или MsgBox-е. 4) Требуется быстрая обработка HTML содержимого, а IE грузит тяжеленную обвязку. Получается что то аля - вместо садового совочка для ковыряния в грядке, мы вызываем экскаватор. <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[Xameleon]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=8836</uri>
			</author>
			<updated>2013-09-10T08:56:22Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75313#p75313</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75258#p75258" />
			<content type="html"><![CDATA[<p>Я дилетант, поэтому то, что скажу, - исключительно моё, ни на что не претендующее, частное мнение.<br />1. Любой объект, содержащий аббревиатуру XML, будет иметь неизлечимые проблемы с незакрытыми тэгами, что, в общем, логично. В XML незакрытого тега не может быть по определению.<br />2. Не думаю, что регулярки помогут в данном случае: всех возможных косяков ни в какой регулярке не предугадаешь. Например, в баннерах может оказаться незакрытым любой тэг, не только тот, что часто не закрывают.<br />3. Может, лучше загружать страницу в объект, который ну просто обязан распарсить страницу, типа InternetExplorer или скрытого фрейма?</p>]]></content>
			<author>
				<name><![CDATA[Serge Yolkin]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=27503</uri>
			</author>
			<updated>2013-09-07T16:29:56Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75258#p75258</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[VBS: Парсинг HTML через MSXML]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=75225#p75225" />
			<content type="html"><![CDATA[<p>Здравствуйте, господа и возможно дамы (давно на форуме не был, возможно что то изменилось). Пришёл к Вам со следующим задачей: <strong>Нужно распарсить&nbsp; HTML документ средствами MSXML</strong>. Да, знаю криво и коряво и вообще так делать нельзя, но с последним апдейтом мелкомягких, <strong>htmlfile</strong> перестал парсить HTML код в ASP. Не буду вдаваться в подробности. Решил попробовать парсить через MSXML.</p><div class="codebox"><pre><code>
Option Explicit
Dim DOMDocument
Set DOMDocument = HTMLToDOMDocument(&quot;&lt;html&gt;&lt;base&gt;&lt;/body&gt;content&lt;/body&gt;&lt;/body&gt;&quot;)

Function HTMLtoDOMDocument(htmlcode)
    Dim DOMDocument: Set DOMDocument = CreateObject(&quot;Msxml2.FreeThreadedDOMDocument.6.0&quot;)
    With DOMDocument
        .validateOnParse = False
        .resolveExternals = False
        .PreserveWhiteSpace = True
        .setProperty &quot;ProhibitDTD&quot;,False
        .setProperty &quot;SelectionLanguage&quot;, &quot;XPath&quot;
        .loadXml htmlcode
        if .parseError &lt;&gt; 0 Then
            With .parseError
                Err.Raise .errorCode, &quot;HTMLtoDOMDocument&quot;, .reason &amp; vbCrlf &amp; &quot;line: &quot; &amp; .line &amp; vbCrlf &amp; &quot;linePos:&quot; &amp; .linePos &amp; vbCrlf &amp; &quot;srcText: &quot; &amp; .srcText
            End With
        End if
    End With
    Set HTMLtoDOMDocument = DOMDocument
End Function
</code></pre></div><p>Наваял вот такую функцию, чтобы МАКСИМАЛЬНО &quot;отговорить&quot; MSXML ругаться на косяки HTML кода, т.к грузить html придётся с разных источников. Но к сожалению <span class="bbu"><strong>от ошибки с незакрытыми тегами пока не получается &quot;отучить&quot;</strong></span>. А такие тэги часто встречаются - &lt;base&gt; &lt;input&gt; &lt;img&gt;</p><p>Предполагаю, что можно решить проблему через RegExp. Рою в этом направлении, но регулярки даются мне очень тяжко. В связи с этим <strong>прошу помощи / совета / рекомендации</strong>.&nbsp; Заранее очень благодарен. )</p>]]></content>
			<author>
				<name><![CDATA[Xameleon]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=8836</uri>
			</author>
			<updated>2013-09-05T16:05:33Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=75225#p75225</id>
		</entry>
</feed>
