首页 > 解决方案 > 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我在这一点上已经做了几次非优雅的方式,只是想知道我是否遗漏了一些东西,以及是否有更好的方法来做到这一点。先感谢您!

标签: pythonbeautifulsoup

解决方案


当前的 HTML 结构非常通用,它包含多个infoEntity带有子内容的 div,可以以多种方式格式化。要处理这个问题,您可以遍历infoEntitydiv 并应用格式化对象,如下所示:

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'}

推荐阅读