如何使用美汤获得多个称号python

How to get multiple titles using beautiful soup python

假设我的文字是

dl class="dl-horizontal">
 <dt title="Name">
  Name
 </dt>
 <dd>
  Phillips
 </dd>
 <dt title="Birth date">
  Birth date
 </dt>
 <dd>
  17/09/1990
 </dd>
 <dt title="Location">
  Location
 </dt>
 <dd>
  Northland
 </dd>
</dl>

我需要提取所有标题如下

Name - Phillips
Birth Date - 17/09/1990
Location - Northland

我想做的是

  list=soup.find_all('title')

但我得到一个空的 列表,而我希望得到标题列表 ['Name'、'Birth Date'、'Location']。

我认为class和ID是更好的解决方案

您需要查找具有特定属性的标签名称

您可以像这样明确指定属性值

soup.find_all('dt', {'title': ['Name', 'Birth date', 'Location']})

或查找任何具有 title

属性的 dt 标签
soup.find_all('dt', {'title': True})

soup.find_all(title=True)

要找到需要使用标签的元素,之后您将需要获取下一个具有该值的元素。

下面给大家举个例子

list = soup.find_all('dt')

dict_to_format = []
for dt_element in list:
    if dt_element.attrs.get('title'):
        target_text = dt_element.find_next_sibling("dd").text.replace("\n", "").strip()
        dict_to_format.append((dt_element.attrs.get('title'), target_text))

print(dict(dict_to_format))

另一种方法:

for a,b in zip(soup.select('dl dt'),soup.select('dl dd')):
    print(a.attrs['title'],b.text.strip())

输出:

Name Phillips
Birth date 17/09/1990
Location Northland