【问题标题】:Return list of names in bs4返回 bs4 中的名称列表
【发布时间】:2014-05-04 19:54:17
【问题描述】:

我正在尝试在 div 中提取前面带有哈希标记的名称。

<div class="h_names">#jason, #michael, #sam, etc...</div>

所以我的结果将是jasonmichaelsam 等的列表。

我不确定如何使用 BeautifulSoup 做到这一点。

import bs4

soup = bs4.BeautifulSoup(html)
div = soup.find('div', {'class' : 'h_names'})

这会找到 div,但我需要一个正则表达式来提取名称

【问题讨论】:

标签: python regex beautifulsoup


【解决方案1】:

这不使用正则表达式,但我认为您不需要使用正则表达式,也不需要导入任何新内容,因为 BeautifulSoup 为您提供了从 html 中提取文本的内置方法。

如果 div 是:

'<div class="h_names">#jason, #michael, #sam</div>' # without the etc.. bit

那么:

div = soup.find('div', {'class' : 'h_names'})
names = [str(name.strip()[1:]) for name in div.text.split(',')]

输出:

>>> print names
['jason', 'michael', 'sam']

names 是使用 list comprehension 创建的。

列表理解中的字符串转换(使用str())是 必要的,因为 div(div.text) 上的 text 方法返回 unicode 字符串(如:u'jason'

[1:]的字符串切片用于切掉每个字符串的第一个字符(本例中为'#')

字符串的strip 方法(str.strip()) 简单地切断任何前导或尾随空格以及换行符(\n)

【讨论】:

    【解决方案2】:

    您可以使用re.findall() 来匹配div 元素内的条件。

    import bs4
    import re
    
    soup  = bs4.BeautifulSoup(html)
    div   = soup.find('div', {'class' : 'h_names'})
    names = re.findall(r'#([a-zA-Z]+)', str(div.text))
    

    输出

    ['jason', 'michael', 'sam']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 2018-11-16
      • 2017-07-10
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多