이것은 내가 지난 주에 질문 하나에 후속 질문입니다 여기에 게시 . 원래 문제는 해결했지만 지금은 약간 다른 문제가 있습니다.
html 태그가 GetAttributeValue 메소드를 사용하여 중첩되지 않은 경우 관심있는 항목의 속성을 가져올 수 있습니다. 여기서는 데이터 -pid 이지만 이제는 항목의 속성을 잡는 데 문제가 있습니다. 중첩 태그에서, 내 코드 단편에서 날짜입니다. xpath와 HtmlAgility 팩을 사용하여 HTML을 파싱합니다. 그러나 아래 예제에서는 동일한 날짜가 반복해서 반환됩니다.
다음은 $ item 객체의 모습입니다.
Attributes : {class, data-pid}
ChildNodes : {#text, a, #text, span...}
Closed : True
ClosingAttributes : {}
FirstChild : HtmlAgilityPack.HtmlTextNode
HasAttributes : True
HasChildNodes : True
HasClosingAttributes : False
Id :
InnerHtml : <a href="/mod/4175126893.html" class="i"><span class="price">$20</span></a> <span class="star"></span> <span class="pl"> <span class="date">Nov
30</span> <a href="/mod/4175126893.html">Unlock Any GSM Cell Phone Today!</a> </span> <span class="l2"> <span class="price">$20</span> <span
class="pnr"> <small> (Des Moines)</small> <span class="px"> <span class="p"> </span></span> </span> <a class="gc" href="/mod/"
data-cat="mod">cell phones - by dealer</a> </span>
InnerText : $20 Nov 30 Unlock Any GSM Cell Phone Today! $20 (Des Moines) cell phones - by dealer
LastChild : HtmlAgilityPack.HtmlTextNode
Line : 305
LinePosition : 5408
Name : p
NextSibling : HtmlAgilityPack.HtmlTextNode
NodeType : Element
OriginalName : p
OuterHtml : <p class="row" data-pid="4175126893"> <a href="/mod/4175126893.html" class="i"><span class="price">$20</span></a> <span class="star"></span>
<span class="pl"> <span class="date">Nov 30</span> <a href="/mod/4175126893.html">Unlock Any GSM Cell Phone Today!</a> </span> <span class="l2">
<span class="price">$20</span> <span class="pnr"> <small> (Des Moines)</small> <span class="px"> <span class="p"> </span></span> </span> <a
class="gc" href="/mod/" data-cat="mod">cell phones - by dealer</a> </span> </p>
OwnerDocument : HtmlAgilityPack.HtmlDocument
ParentNode : HtmlAgilityPack.HtmlNode
PreviousSibling : HtmlAgilityPack.HtmlTextNode
StreamPosition : 18733
XPath : /html[1]/body[1]/article[1]/section[1]/div[1]/div[2]/p[11]
Attributes : {class, data-pid}
ChildNodes : {#text, a, #text, span...}
Closed : True
ClosingAttributes : {}
outerhtml 값에서 데이터를 가져 오려고 합니다.
OuterHtml : <p class="row" data-latitude="41.5937565437255" data-longitude="-93.6437636649079" data-pid="4184719674"> <a href="/mod/4184719674.html" class="i"></a>
<span class="star"></span> <span class="pl"> <span class="date">Nov 27</span> <a href="/mod/4184719674.html">iPhone and other Cell Phone Unlocks</a>
</span> <span class="l2"> <span class="pnr"> <small> (Des Moines)</small> <span class="px"> <span class="p"> <a href="#" class="maptag"
data-pid="4184719674">map</a></span></span> </span> <a class="gc" href="/mod/" data-cat="mod">cell phones - by dealer</a> </span> </p>
나는 데이터 pid를 잡을 수있다. 다음은 현재 코드의 모습입니다.
ForEach ($item in $results) {
# This is working
$ID = $item.GetAttributeValue("data-pid", "")
# This is looping over the same item
$Date = $item.SelectSingleNode("//span[@class='date']").InnerText
}
내가 뭘하고 싶은 건 내 xpath 문을 사용하여 outerhtml 개체에 포함 된 다른 태그의 특성을 잡을 수 있지만 어떻게 해야할지 알아낼 수 없습니다. 그게 문제에 대해 갈 수있는 최선의 방법인가, 아니면 그냥 내가 원하는 값을 얻기 위해 일부 정규식을 사용해야합니까?
제가 게시해야 할 다른 세부 정보를 알려주십시오.
HTML 애자일 팩을 사용하지는 않았지만 AFAICS 기본 제공 도구로 충분해야합니다.
$url = 'http://www.example.com/path/to/some.html'
$html = (Invoke-Webrequest $url).ParsedHTML
$html.getElementsByTagName('p') | ? { $_.className -eq 'row' } | % {
$ID = $_.getAttributeNode('data-pid').value
$Date = $_.getElementsByTagName('span') | ? { $_.className -eq 'date' } |
% { $_.innerText }
# do stuff with $ID and $Date
"{0}: {1}" -f $ID, $Date
}
Invoke-Webrequest
에는 PowerShell v3이 필요합니다. PowerShell v2로 제한된 경우 Internet Explorer COM 개체를 사용하십시오.
$ie = New-Object -COM InternetExplorer.Application
$ie.Navigate($url)
while ($ie.ReadyState -ne 4) { sleep 100 }
$html = $ie.Document
HTML 파일이 로컬 파일 인 경우 Invoke-Webrequest
행을 다음과 같이 Invoke-Webrequest
.
$htmlfile = 'C:\path\to\some.html'
$html = New-Object -COM HTMLFile
$html.write((Get-Content $htmlfile | Out-String))
나는 너무 늦었지만 여기 당신의 실수입니다. 당신은 절대 경로를 사용하고 있습니다.
ForEach ($item in $results) {
# This is working
$ID = $item.GetAttributeValue("data-pid", "")
# This is looping over the same item
$Date = $item.SelectSingleNode("//span[@class='date']").InnerText
# This is looping over the different items (i.e. this is what what you want)
$Date = $item.SelectSingleNode(".//span[@class='date']").InnerText
}