【问题标题】:How to get only nececcary <div> with Python Beautifulsoup如何使用 Python Beautifulsoup 只获取必需的 <div>
【发布时间】:2022-07-07 16:56:22
【问题描述】:

我需要从 wikidata 解析一些关于作者的信息。我用 Python Beautifulsoup

页面:https://www.wikidata.org/wiki/Q39829

问题

我需要解析页面中的“child”字段。结果我想得到 3 个名字。但不是 3 个名字,而是 3 个名字 + 2 个额外值。

代码

children_html = soup.find('div', id='P40').find_all('div', class_='wikibase-snakview-variation-valuesnak')
children_list = [child.text.strip() for child in children_html]
print(children_list)

结果是:

['Joe Hill', 'Owen King', 'Naomi King', 'https://books.google.de/books?id=aPBbAgAAQBAJ', '81']

问题

有没有办法在结果中只获取名称:

['Joe Hill', 'Owen King', 'Naomi King']

该代码也应该适用于其他作家页面。谁可以有更少或更多的孩子

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    你可以通过列表切片来做到这一点

    names = [x.get_text() for x in soup.find('div', id='P40').find_all('div', class_='wikibase-snakview-variation-valuesnak')][0:3]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      相关资源
      最近更新 更多