首页 > 解决方案 > 如何在正则表达式中使用括号获得多个数字

问题描述

我试图在 python3 中使用 urllib 和正则表达式从 html 代码中提取值,当我尝试运行此代码时,它只给了我一个数字而不是两个值,即使我添加了一个“+”符号表示一次或多次。这里有什么问题?

import re
import urllib.error,urllib.parse,urllib.request
from bs4 import BeautifulSoup
finalnums=[]
sumn=0
urlfile = urllib.request.urlopen("http://py4e-data.dr-chuck.net/comments_42.html")

html=urlfile.read()
soup = BeautifulSoup( html,"html.parser" )
spantags = soup("span")
for span in spantags:
    span=span.decode()  
    numlist=re.findall(".+([0-9].*)<",span)
    print(numlist)
    finalnums.extend(numlist)
for anum in finalnums:
    sumn=sumn+int(anum)
print("Sum = ",sumn)

这是我试图从中提取数字的字符串示例:

 <span class="comments">54</span>

标签: pythonregexweb-scraping

解决方案


用于numlist=re.findall("\d+",span)搜索所有连续的数字字符组。

\d是一个相当于 的字符类[0-9],所以如果你这样做它也可以工作numlist=re.findall("[0-9]+",span)


推荐阅读