【问题标题】:Separating tag attributes as a dictionary将标签属性分离为字典
【发布时间】:2022-08-16 21:07:40
【问题描述】:

我的条目(变量是字符串类型):

<a href=\"https://wikipedia.org/\" rel=\"nofollow ugc\">wiki</a>

我的预期输出:

{
\'href\': \'https://wikipedia.org/\',
\'rel\': \'nofollow ugc\',
\'text\': \'wiki\',
}

我怎样才能用 Python 做到这一点?不使用 beautifulsoup 库
请在lxml库的帮助下告诉

  • 使用lxml 而不是beautifulsoup
  • 链接文本不是属性
  • 您可以尝试使用regex,但在某些情况下它可能是非常复杂的任务,因此最好使用beautifulsouplxml 或类似模块。
  • @Curiouskoala 没错,感谢您帮助我找到答案。

标签: python python-3.x web-scraping web-crawler


【解决方案1】:

正则表达式的解决方案:

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'}

【讨论】:

  • 谢谢回复。有没有办法借助 lxml 库获取文本?
【解决方案2】:

在使用BeautifulSoup 时,您可以使用.attrs 来获取标签属性的dict

from bs4 import BeautifulSoup
soup = BeautifulSoup('<a href="https://wikipedia.org/" rel="nofollow ugc">wiki</a>')
soup.a.attrs

--> {'href': 'https://wikipedia.org/', 'rel': ['nofollow', 'ugc']}

要获取文本:

...
data = soup.a.attrs
data.update({'text':soup.a.text})
print(data)

--> {'href': 'https://wikipedia.org/', 'rel': ['nofollow', 'ugc'], 'text': 'wiki'}

【讨论】:

  • 谢谢回复。您可以借助 lxml 库来判断吗?
  • 这是问题作者弃用的 BeautifulSoup 的解决方案 :) 通过 bs,使用一些神奇的 lambda 函数可以很容易地解压缩任何 lxml 结构。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
相关资源
最近更新 更多