python - BeautifulSoup - 处理类似网站结构的表格|返回字典
问题描述
我有一些 html,那种看起来像字典:
制造商网站:网站,
总部:位置等..
每个部分都包含在自己的 div 中(所以 findAll,div 类名)。
是否有一种优雅而简单的方法可以将此类代码提取到字典中?或者是否必须遍历每个 div,找到两个文本项,并假设第一个文本项是字典的键,第二个值是同一个 dict 元素的值。
示例站点代码:
car = '''
<div class="info flexbox">
<div class="infoEntity">
<span class="manufacturer website">
<a class="link" href="http://www.ford.com" rel="nofollow noreferrer" target="_blank">
www.ford.com
</a>
</span>
</div>
<div class="infoEntity">
<label>
Headquarters
</label>
<span class="value">
Dearbord, MI
</span>
</div>
<div class="infoEntity">
<label>
Model
</label>
<span class="value">
Mustang
</span>
</div>
'''
car_soup = BeautifulSoup(car, 'lxml')
print(car_soup.prettify())
elements = car_soup.findAll('div', class_ = 'infoEntity')
for x in elements:
print(x) ###and then we start iterating over x, with beautiful soup, to find value of each element.
想要的输出是这个
expected result result = {'manufacturer website':"ford.com", 'Headquarters': 'Dearborn, Mi', 'Model':'Mustang'}
PS我在这一点上已经做了几次非优雅的方式,只是想知道我是否遗漏了一些东西,以及是否有更好的方法来做到这一点。先感谢您!
解决方案
当前的 HTML 结构非常通用,它包含多个infoEntity
带有子内容的 div,可以以多种方式格式化。要处理这个问题,您可以遍历infoEntity
div 并应用格式化对象,如下所示:
from bs4 import BeautifulSoup as soup
result, label = {}, None
for i in soup(car, 'html.parser').find_all('div', {'class':'infoEntity'}):
for b in i.find_all(['span', 'label']):
if b.name == 'label':
label = b.get_text(strip=True)
elif b.name == 'span' and label is not None:
result[label] = b.get_text(strip=True)
label = None
else:
result[' '.join(b['class'])] = b.get_text(strip=True)
输出:
{'manufacturer website': 'www.ford.com', 'Headquarters': 'Dearbord, MI', 'Model': 'Mustang'}
推荐阅读
- javascript - 使用 react-redux 时,prevProps 和 this.props 将始终在 componentDidUpdate 中返回相同的值
- mysql - MySQL - 多个并发更新
- c - 第 25 行中的运行时错误:字符 35:运行时错误:“struct HASH_TABLE”类型的空指针内的成员访问(solution.c)
- android - 如何在不使用库的情况下在状态、焦点和正常状态下应用自定义形状的 TextInputLayout
- python - 记录学生姓名的功能
- xcode - 图像作为图标外观
- c - 即使我包含 unistd.h 在内核代码中隐式声明 getpid
- amazon-web-services - 如何使用 Eclipse JEE 从我的 Web 应用程序登录到 AWS?
- java - Java - 解释对象文件
- java - 使用 JTransforms 的 FFT:是基数 2 吗?