【问题标题】:Extract information from html list to pandas df/list/dict (python 3.0)从 html 列表中提取信息到 pandas df/list/dict (python 3.0)
【发布时间】:2018-10-12 17:43:49
【问题描述】:

我有一个包含多个列表的网站的源代码。现在我想将这些列表的信息提取成python中可用的格式。

例如,请参阅下面国家列表的第一个列表条目:

<ul class='checklist__list'>

    <li class=' checklist__item' id='checklist__item--country-111'>
      <label class='checklist__label ripple-animation'>
        <input  class="checklist__input js-checklist__input idb-on-change" type="checkbox" id="111" name="country" value="111">
          Germany
        </input>
      </label>
    </li>

说,我现在对国家 ID(此处:111)和匹配的国家/地区名称(此处:德国)感兴趣,并希望在 python 中以可用的格式使用它,例如 pandas 数据框或字典。

有没有人知道一个简单的方法来做到这一点?原始列表包含 >100 个国家/地区。

非常感谢您的建议!

【问题讨论】:

  • 看起来漂亮的汤在这里很容易

标签: python html list pandas html-lists


【解决方案1】:

BeautifulSoup 可以轻松解决这个问题。 鉴于您在问题中发布的标记,此代码 sn-p 应提取 idlabel

from bs4 import BeautifulSoup as bs
html = """<ul class='checklist__list'>
            <li class=' checklist__item' id='checklist__item--country-111'>
              <label class='checklist__label ripple-animation'>
              <input  class="checklist__input js-checklist__input idb-on-change" type="checkbox" id="111" name="country" value="111">
                Germany
              </input>
              </label>
            </li>"""

soup = bs(html)
label = soup.find("label").text
id = soup.find("input").get("value")

您必须清理标签,因为输出中有一些多余的空格和换行符,但是您应该能够扩展此示例,但是您需要进一步处理这些项目。

要处理多个与上述标记格式相同的列表项,可以使用这个sn-p:

lis = soup.find_all("li")  # This will return a list of all line items in the markup.
for li in lis:
    li_label = li.find("label").text
    li_id = li.find("input").get("id")
    print(li_label, li_id)

【讨论】:

  • 谢谢,效果很好!我用以下行删除了空格和换行符li_country= ' '.join(li.find("label").text.split())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
相关资源
最近更新 更多