首页 > 解决方案 > 使用 beautifulsoup 将 ul 类中的详细信息解析为 dict

问题描述

下面是我使用 selenium 和 beautifulsoup 编写的代码。我正在使用它来筛选从 zillow 中抓取一些有关房价的信息。我正在根据邮政编码进行抓取。我可以通过使用 find_all 拉取 ul 类来获取家庭详细信息,下面是我当前代码和输出的示例。我想做的是将 find_all 的输出进一步解析为一个字典,其中家庭详细信息作为键,值作为值。我在下面包含了一个示例输出。谁能建议如何做到这一点?

代码:

import pandas as pd
import numpy as np

import os

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


Options

options = Options()

chrome_options = Options() 


driver = webdriver.Chrome(executable_path=os.path.abspath("chromedriver"), chrome_options=chrome_options)


#re allows for matching text with regular expressions (including through BeautifulSoup)
#dateutil.parser provies .parse() to convert plain text dates in a variety of formats into datetime objects
import re, dateutil.parser
#BeautifulSoup provide a model for the source HTML
from bs4 import BeautifulSoup

#Webdriver is interface to the selected browser (PhantomJS)
from selenium import webdriver
#Ability to select values in HTML <select> tags
from selenium.webdriver.support import select
import time


from selenium.webdriver.common import action_chains, keys

driver.get(zip_url)

tstsoup = BeautifulSoup(driver.page_source)

zip_url = 'https://www.zillow.com/homes/for_sale/95536_rb/'

tstsoup.find_all('ul',{'class':'list-card-details'})

输出:

<ul class="list-card-details"><li class="">4<abbr class="list-card-label"> <!-- -->bds</abbr></li><li class="">2<abbr class="list-card-label"> <!-- -->ba</abbr></li><li class="">2,172<abbr class="list-card-label"> <!-- -->sqft</abbr></li><li class="list-card-statusText">- House for sale</li></ul>

所需的输出:

{'bds:4,'ba':2,'sqft':2,172}

标签: python-3.xselenium-webdriverweb-scrapingbeautifulsoup

解决方案


我已将数据作为 html 并li在 html 中查找,其中数据被拆分以查找作为字典的键和值对d并附加到列表中lst,该列表制作字典列表

html="""<ul class="list-card-details"><li class="">4<abbr class="list-card-label"> <!-- -->bds</abbr></li><li class="">2<abbr class="list-card-label"> <!-- -->ba</abbr></li><li class="">2,172<abbr class="list-card-label"> <!-- -->sqft</abbr></li><li class="list-card-statusText">- House for sale</li></ul>
"""
soup = BeautifulSoup(html, 'html.parser')
main_data=soup.find_all('ul',{'class':'list-card-details'})
lst=[]
for data in main_data:
    d={  i.text.split(" ")[1] : i.text.split(" ")[0] for i in data.find_all("li",class_="")   }
    lst.append(d)
print(lst[0])

输出:

{'bds': '4', 'ba': '2', 'sqft': '2,172'}

推荐阅读