【问题标题】:Using regex with Beautiful soup将正则表达式与美丽的汤一起使用
【发布时间】:2017-12-14 02:11:18
【问题描述】:

我在尝试将正则表达式与漂亮的汤一起使用时遇到了一点麻烦。

我的html如下:

[<strong>See the full calendar</strong>, <strong>See all events</strong>, <strong>See all committee meetings</strong>, <strong>526 spaces</strong>, <strong>89 spaces</strong>, <strong>53 spaces</strong>, <strong>154 spaces</strong>, <strong>194 spaces</strong>, <strong>See all news releases</strong>]
[<strong>See the full calendar</strong>, <strong>See all events</strong>, <strong>See all committee meetings</strong>, <strong>526 spaces</strong>, <strong>89 spaces</strong>, <strong>53 spaces</strong>, <strong>154 spaces</strong>, <strong>194 spaces</strong>, <strong>See all news releases</strong>]

我想要的只是强标签之间的空格数。

我尝试过使用:

print(soup.find_all(re.compile("\d\d\d\s[a-zA-Z]{6}|(strong)")))

但是,这将返回 print(soup.find_all('strong')) 所做的一切。

有人知道我哪里出错了吗?

【问题讨论】:

  • 谢谢!试过print(len(soup.find_all('strong').split())-1) 但得到AttributeError: 'ResultSet' object has no attribute 'split' - 有什么想法吗? @Ludisposed
  • 你想要所有空格的总和还是每个强标签都应该有它自己的空格计数器?
  • 最终目标是将其导出为 csv,因此每个“x 个空格”需要是每一行的单独记录

标签: python regex web-scraping beautifulsoup


【解决方案1】:

如果我理解正确,您可以使用soup.find_all 的text 属性,并传递一个编译的正则表达式模式:

import re
spaces = []
for tag in content.find_all(text=re.compile("\d+(?= spaces)")):
    spaces.append(int(tag.string.split()[0]))

print(spaces)

输出:

[526, 89, 53, 154, 194, 526, 89, 53, 154, 194]

【讨论】:

  • 现在我很困惑OP想要什么,空格数或强标签中空格前的数字。使用 text 属性是一个我不知道的好功能
  • @Ludisposed 因此,“如果我理解正确的话”,哈哈。 OP提到了空格,并且有一堆以xxx空格为内容的标签,所以我认为这就是他们的意思。
  • 重读后是的:OP:“所以每个x个空格”我认为你是对的
  • 谢谢两位,是的,这就是我要找的! - 对不起,如果我的帖子令人困惑?!
【解决方案2】:

首先找到所有强标签

strong_tags = soup.find_all('strong')
spaces_in_tags = {}

# Afterwards iterate over the tags.. Then do either

for strong in strong_tags:
    # 1. (EDIT add \s+ so multiple spaces between words will count as 1 space)
    number_of_spaces = len(re.findall('\s+', strong))
    # 2.
    number_of_spaces2 = len(strong.split())-1

    # Then add them do a dictionary/list whatever suits your need
    # For example to have the string as the key parameter in a dictionary
    spaces_in_tags[strong] = number_of_spaces

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-21
    • 2012-05-05
    • 2014-09-05
    • 2013-06-29
    • 1970-01-01
    • 2013-06-19
    • 2013-04-09
    相关资源
    最近更新 更多