正则表达式的解决方案:
import re
pattern_text = r"[>](\w+)[<]"
pattern_href = r'href="(\w\S+)"'
pattern_rel = r'rel="([A-z ]+)"'
xml = '<a href="https://wikipedia.org/" rel="nofollow ugc">wiki</a>'
dict_ = {
'href': re.search(pattern_href, xml).group(1),
'rel': re.search(pattern_rel, xml).group(1),
'text': re.search(pattern_text, xml).group(1)
}
print(dict_)
>>> {'href': 'https://wikipedia.org/', 'rel': 'nofollow ugc', 'text': 'wiki'}
如果输入是字符串,它将起作用。
也可以使用 lxml 解决方案(但没有bs!):
from lxml import etree
xml = '<a href="https://wikipedia.org/" rel="nofollow ugc">wiki</a>'
root = etree.fromstring(xml)
print(root.attrib)
>>> {'href': 'https://wikipedia.org/', 'rel': 'nofollow ugc'}
但是没有text 属性。
您可以使用text 属性提取它:
print(root.text)
>>> 'wiki'
得出结论:
from lxml import etree
xml = '<a href="https://wikipedia.org/" rel="nofollow ugc">wiki</a>'
root = etree.fromstring(xml)
dict_ = {}
dict_.update(root.attrib)
dict_.update({'text': root.text})
print(dict_)
>>> {'href': 'https://wikipedia.org/', 'rel': 'nofollow ugc', 'text': 'wiki'}