2011-09-19 6 views
2

나는 이런 식으로 뭔가가 있다고 가정 : 나는 http://example.com/image.jpgwhat the file is actually called.jpg이다에서 추출 할 무엇Python + XPath : 실제로 원하는 것 다음 요소를 선택할 수 있습니까?

<span class="filesize">File<a href="http://example.com/image.jpg" 
target="_blank">image.jpg</a>-(1.61 MB, 1000x1542, <span title="what the file is actually 
called.jpg">what the file is actually called.jpg</span>)</span><br><a href="http://example.com 
/image.jpg" target="_blank"> 

. 상수 용어는 xpath("span[text()='File']")을 사용하여 찾을 수 있지만 span에만 액세스 할 수있는 <span class="filesize">File입니다. 나중에 링크로 이동하려면 result += 1과 같은 작업을 수행 한 다음 파일 이름 뒤에 span을 입력하십시오.

답변

2

xpath "축"은 following-siblingpreceding-sibling xpath를 사용하여 필요한 탐색을 할 수 있습니다. 억류를받을 수 있습니다 here.

는 편집 :

다음은 나에게 당신은 XPath를 사용하여 원하는 결과를 가져 오는 예입니다. 그러나 주위의 XML이 무엇인지에 따라 작동하지 않을 수도 있습니다. (일부 태그를 "실제"XML로 완성해야합니다. XML을 배치하지 않고도 작동시킬 수 있습니다. 파서를 HTML 모드로 ...)

import lxml.etree 

xml = lxml.etree.XML("""<something><span class="filesize">File<a href="http://example.com/image.jpg" target="_blank">image.jpg</a>-(1.61 MB, 1000x1542, <span title="what the file is actually called.jpg">what the file is actually called.jpg</span>)</span><br/><a href="http://example.com/image.jpg" target="_blank"></a></something>""",) 

print xml.xpath("a[preceding-sibling::span/text()='File']/@href") 
+0

이제'getnext()'및'getprevious()'메소드가 있습니다. 거기에 xpath 안에 그들을 사용하는 더 pythonic 방법, 그래서 내가 목록 안의 각 요소에 액세스하고 코드를 더 이상 만들 필요가 없어? – slackingagain

+0

XPath 만 사용하는 방법에 대한 자세한 내용을 추가했습니다. –

관련 문제