1

Я не понимаю, как сделать нормальный вывод тега

URL = 'https://imgur.com/iTZUi2Q'# + random_e(7)
page = requests.get(URL, headers={'User-Agent': 'Mozilla/5.0'})
parsed_body = html.document_fromstring(page.text)
image = parsed_body.xpath('//div')

Вывод:

[<Element div at 0x35fcf90>, <Element div at 0x35fcfc0>, <Element div at 0x3642030>, <Element div at 0x3642060>]

А хотелось по типу:

['<div id="test">',.....]

1 ответ 1

1

Используйте метод tostring, пример:

from lxml import html

...

def to_str(root):
    return html.tostring(root, encoding='unicode')

images = parsed_body.xpath('//div')

print([to_str(node) for node in images])

PS.

Наглядный пример использования tostring:

Для парсинга html:

from lxml import html
root = html.fromstring('<p>Hello<br>world!</p><br>')

print(html.tostring(root))                      # b'<div><p>Hello<br>world!</p><br></div>'
print(html.tostring(root, encoding='unicode'))  # <div><p>Hello<br>world!</p><br></div>
print(html.tostring(root, pretty_print=True))   # b'<div>\n<p>Hello<br>world!</p>\n<br>\n</div>\n'
print(html.tostring(root, encoding='unicode', pretty_print=True))
# <div>
# <p>Hello<br>world!</p>
# <br>
# </div>

Для парсинга xml:

from lxml import etree
root = etree.fromstring('<a><b>Hello</b><c>world!</c></a>')

print(etree.tostring(root))                      # b'<a><b>Hello</b><c>world!</c></a>'
print(etree.tostring(root, encoding='unicode'))  # <a><b>Hello</b><c>world!</c></a>
print(etree.tostring(root, pretty_print=True))   # b'<a>\n  <b>Hello</b>\n  <c>world!</c>\n</a>\n'
print(etree.tostring(root, encoding='unicode', pretty_print=True))
# <a>
#   <b>Hello</b>
#   <c>world!</c>
# </a>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.