Найти - Пользователи
Полная версия: XPath вопрос на примере
Начало » Python для новичков » XPath вопрос на примере
1
agryn
Есть пример html-кода
<html>
    <div class="myclass">
        <p>
            some html code
        </p>
        <br>
            some html code 2       
    </div>
</html>

если прописать
 '//div[@class="myclass"]'
то извлекаться
    <div class="myclass">
        <p>
            some html code
        </p>
        <br>
            some html code 2       
    </div>
а как извлечь?
        <p>
            some html code
        </p>
        <br>
            some html code 2    
mironich
 '//div[@class="myclass"]/p' #Для some html code
        <p>
            some html code
        </p>
        <br>
            some html code 2  
У библиотеки lxml есть у обьектов(HTMLElement) атрибут text.
py.user.next
>>> s = """
... <html>
...     <div class="myclass">
...         <p>
...             some html code
...         </p>
...         <br>
...             some html code 2       
...     </div>
... </html>
... """
>>> 
>>> root = lxml.html.fromstring(s)
>>> elems = root.xpath('//div[@class="myclass"]/*')
>>> for i in elems:
...     print('<{0}> <{1}>'.format(i.tag, i.text))
... 
<p> <
            some html code
        >
<br> <None>
>>>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB