Например, а более подробно смотреть в документации приведенных модулей.
Входные данные:
text = '''<div>
<ul><a href="http://test.ru/12345" >test1</a></ul>
<ul><a href="http://test.ru/56789" >test2</a></ul>
<ul><a href="http://test.ry/34567" >test3</a></ul>
</div>
'''
Решение через lxml
(только с tostring
получится получить HTML):
# pip install lxml
from lxml import etree
root = etree.fromstring(text)
items = root.xpath('//a')
print(items)
print('href:', items[0].attrib['href'])
print('tag:', etree.tostring(items[0], encoding='unicode'))
print()
for a in items:
print('a:', etree.tostring(a, encoding='unicode'))
print()
print()
Консоль:
[<Element a at 0x2dae708>, <Element a at 0x2dae748>, <Element a at 0x2dae788>]
href: http://test.ru/12345
tag: <a href="http://test.ru/12345">test1</a>
a: <a href="http://test.ru/12345">test1</a>
a: <a href="http://test.ru/56789">test2</a>
a: <a href="http://test.ry/34567">test3</a>
Решение через bs4
(достаточно запросить текстовое представление):
# pip install bs4
from bs4 import BeautifulSoup
root = BeautifulSoup(text, 'lxml')
items = root.select('a')
print(items)
a = items[0]
print('href:', a['href'])
print('tag:', a)
Консоль:
[<a href="http://test.ru/12345">test1</a>, <a href="http://test.ru/56789">test2</a>, <a href="http://test.ry/34567">test3</a>]
href: http://test.ru/12345
tag: <a href="http://test.ru/12345">test1</a>