【问题标题】:Python, Beautiful soup, <br> tagPython, 美丽的汤, <br> 标签
【发布时间】:2019-03-03 21:22:37
【问题描述】:

所以我查看了堆栈溢出,但似乎找不到我的问题的答案。如何在 标签之后获取文本、特定文本?

这是我的代码:

product_review_container = container.findAll("span",{"class":"search_review_summary"})
for product_review in product_review_container:
    prr = product_review.get('data-tooltip-html')
    print(prr)

这是输出:

Very Positive<br>86% of the 1,013 user reviews for this game are positive.

我希望在这个字符串中只有 86% 和 1,013。所以只有数字。但是它不是 int,所以我不知道该怎么做。

这里是文本的来源:

   [<span class="search_review_summary positive" data-tooltip-html="Very Positive&lt;br&gt;86% of the 1,013 user reviews for this game are positive.">
</span>]

这是我获取信息的链接:https://store.steampowered.com/search/?specials=1&page=1

谢谢!

【问题讨论】:

  • 你可以使用正则表达式

标签: python beautifulsoup tags


【解决方案1】:

你需要在这里使用正则表达式!

import re

string = 'Very Positive<br>86% of the 1,013 user reviews for this game are positive.'
a = re.findall('(\d+%)|(\d+,\d+)',string)
print(a)

output: [('86%', ''), ('', '1,013')]
#Then a[0][0] will be 86% and a[1][1] will be 1,013

其中 \d 是字符串中的任意数字字符,+ 表示至少有 1 个或多个数字。

如果您需要更具体的正则表达式,可以在https://regex101.com 中尝试

【讨论】:

  • 谢谢!这行得通,我在 1,013 之间遇到了一点问题。不得不把它变成一个 . (dot) 然后做 replace(",","") 但它现在可以工作了:)
【解决方案2】:

有一种非正则表达式的方法;诚然有些令人费解,但仍然很有趣:

首先,我们借用(和修改)this nice function:

def split_and_keep(s, sep):
         if not s: return [''] # consistent with string.split()
         p=chr(ord(max(s))+1)
         return s.replace(sep, sep+p).split(p)

然后我们通过一些标准步骤:

html = """
  [<span class="search_review_summary positive" data-tooltip-html="Very    Positive&lt;br&gt;86% of the 1,013 user reviews for this game are positive."></span>]
  """

from bs4 import BeautifulSoup as bs4
soup = bs4(html, 'html.parser')
info = soup.select('span')[0].get("data-tooltip-html")
print(info)

目前的输出是:

Very Positive<br>86% of the 1,013 user reviews for this game are positive.

接下来我们开始:

data = ''.join(c for c in info if (c.isdigit()) or c == '%')
print(data)

现在输出稍微好一点:

86%1013

快到了;现在是pièce de résistance

split_and_keep(data, '%')

最终输出:

['86%', '1013']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 2016-03-22
    相关资源
    最近更新 更多