我目前正在尝试从网页中抓取一些数据。我需要的数据在 <meta> 内html 源代码的标记。使用 BeautifulSoup 抓取数据并将其保存为字符串是没有问题的。
该字符串包含 2 个我要提取的数字。这些数字(1-100 的评分)中的每一个都应分配给一个不同的变量以供进一步处理。
test_str = "<meta content=\"Overall Rating: 79/100 ... Some Info ... Score: 86/100 \"/>"
第一个值为79/100第二个是86/100 , 但我只需要 79和 86 .到目前为止,我已经创建了一个正则表达式搜索来查找这些值,然后是 .replace("/100")。清理一切。
但是在我的代码中,我只获得了第一个正则表达式搜索匹配项的值,即 79 .我尝试使用 m.group(1) 获取第二个值但它不起作用。
我错过了什么?
test_str = "<meta content=\"Overall Rating: 79/100 ... Some Info ... Score: 86/100 \"/>"
m = re.search("../100", test_str)
if m:
found = m.group(0).replace("/100","")
print found
# output -> 79
感谢您的帮助。
最好的问候!
请您参考如下方法:
test_str = "<meta content=\"Overall Rating: 79/100 ... Some Info ... Score: 86/100 \"/>"
m = re.findall('(\d+(?=\/100))', test_str)
# m = ['79', '86']
我将 .. 更改为 /d+ 因此您可以搜索 1 位或 2 位
我还使用了积极的前瞻性 (?=...),所以 .replace 变得不必要了
例子在 Regex101
