我有一个包含几个列表的网站的源代码。现在,我想将这些列表的信息提取为可用的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中可用的格式,例如熊猫数据框或字典。

有人知道这样做的简单方法吗?原始列表包含100多个国家。

非常感谢您的建议!

最佳答案

您可以使用BeautifulSoup轻松解决此问题。
给定您在问题中发布的标记,此代码段应提取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")


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

要处理多个具有与上述相同的标记格式的列表项,可以使用以下代码段:

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)

关于python - 从html列表中提取信息到pandas df/list/dict(python 3.0),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50137612/

10-12 07:32