python-3.x - 使用 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}
解决方案
我已将数据作为 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'}
推荐阅读
- angular - 印度电话号码的指令在角度 8 中不起作用
- javascript - 在“仅较小的显示”中限制 Chart.js 上的标签数量
- javascript - Sendgrid,Firebase 电子邮件未使用 Netlify 在生产中发送
- javascript - QuaggaJs:条码扫描器的浏览器兼容性问题
- swift - 核心数据 - 使用 NSPredicate 的 NSFetchedResultsController
- java - Android Listview 自动滚动使项目不可见
- jquery - 在响应模式数据表上仅显示两个字段
- html - Css在中心水平和垂直对齐项目
- django - Wagtail:编译项目时文件路径错误
- javascript - 如何在我的代码 later.on 中使用在事件内部生成的变量(Leflet 层数组)