【问题标题】:Get first instance of text for parent item in BeautifulSoup获取 BeautifulSoup 中父项的第一个文本实例
【发布时间】:2017-09-21 16:49:47
【问题描述】:

我有以下 HTML:

<div>


  <h5>Item1</h5>
  $14.00<br>
  <br>

  <h5>Item2</h5>
  $16.29 (Shop Rite)<br>
  $15.49 (Costco)<br>
  <br>

  <h5>Item3</h5>
  ...
</div>

我正在尝试根据项目编号将此信息组织到一个列表中,如下所示:

+--------+--------------------+
| Item1  | $14.00 (BJs)       |
| Item2  | $16.29 (Shop Rite) |
| Item2  | $15.49 (Costco)    |
+--------+--------------------+

我想要类似以下的东西:

Items = []
if (BS.find('h5', text="Item1")):
  for content in BS.find('h5', text="Item1").parent:
    Price = BS.find('h5', text="Item1").parent.content[0]
    Items.append("Item1", Price)

我的主要目标是能够单独获取由&lt;br&gt; 标签分隔的文本,然后将其存储到名为Items 的列表中,但我不确定如何遍历每个&lt;br&gt; 标签&lt;div&gt; 标签基于&lt;h5&gt; 标签。

【问题讨论】:

    标签: python html text beautifulsoup parent-child


    【解决方案1】:

    我建议您将收集到的数据收集在类似字典的对象中而不是列表中,这样您就可以将多个价格与每个标题文本相关联。我使用了 defaultdictlist 类型。

    首先找到h5 元素的集合。然后找到每个兄弟姐妹的集合。但是请注意,第二个和第三个 h5 元素是第一个元素的兄弟,例如,这意味着,在处理任何给定 h5 的兄弟时,我们希望在遇到 another @987654326 时停止@。当我们看到这一点时,我们break。以类似的方式,当我们遇到br 元素时,我们会忽略它;我们continue 继续下一个兄弟姐妹。然后,如果兄弟是空的,但对于空白,我们也会忽略它。

    最后,通过这些测试的项目被添加到字典中。

    >>> import bs4
    >>> soup = bs4.BeautifulSoup(open('temp.htm').read(), 'lxml')
    >>> from collections import defaultdict
    >>> info = defaultdict(list)
    >>> for h5 in soup.findAll('h5'):
    ...     for item in h5.next_siblings:
    ...         if item.name == 'br':
    ...             continue
    ...         if item.name == 'h5':
    ...             break
    ...         if not item.strip():
    ...             continue
    ...         info[h5.text].append(item.strip())
    ... 
    

    我们可以这样显示字典的内容。我把它留给你来适当地格式化它。

    >>> info
    defaultdict(<class 'list'>, {'Item1': ['$14.00'], 'Item3': [], 'Item2': ['$16.29 (Shop Rite)', '$15.49 (Costco)']})
    >>> for item in info:
    ...     for price in info[item]:
    ...         item, price
    ...         
    ('Item1', '$14.00')
    ('Item2', '$16.29 (Shop Rite)')
    ('Item2', '$15.49 (Costco)')
    

    【讨论】:

      猜你喜欢
      • 2016-03-26
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2021-10-07
      • 1970-01-01
      • 2014-11-24
      • 2021-12-25
      相关资源
      最近更新 更多