python - 我已经编写了一个代码来查找html 链接中的标签,并提取每个标签中的数字并进行总结。我正在获取第 17 行的回溯
问题描述
我已经编写了一个代码来查找 html 链接中的标签,并提取每个标签中的数字并进行总结。我正在获取第 17 行的回溯
# import from library
import urllib.request, urllib.parse, urllib.error
import re
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Create socket and send GET
url = 'http://py4e-data.dr-chuck.net/comments_869869.html'
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all of the span tags
lst = list()
tags = soup('span')
for tag in tags:
no = re.findall('[0-9]+',tag)
num = int(no)
lst.append(num)
print(sum(lst))
解决方案
您必须提供字符串才能re.findall
运行。这是更正的示例:
import re
import ssl
import urllib.request
from bs4 import BeautifulSoup
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Create socket and send GET
url = 'http://py4e-data.dr-chuck.net/comments_869869.html'
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all of the span tags
lst = list()
tags = soup('span')
for tag in tags:
no = re.search(r'([\d]+)',tag.text).group(1) # <-- tag.text
num = int(no)
lst.append(num)
print(sum(lst))
印刷:
2468
推荐阅读
- excel - 每次循环迭代后更新 Excel 中的图表
- javascript - 忽略全局 SCSS Webpack CSSModule
- django - 如何在 django 中实现微服务并使它们相互通信
- sql-server - 成功插入后如何从存储过程发送邮件:MSSQL 2017
- reporting-services - SSRS - 根据其他 2 列的条件从数据集中的列中提取值
- bash - 在 bash 中,查找相关文件不存在的文件列表
- ios - 与导航控制器一起使用时,UITabBarItem 的标题不显示
- angularjs - 解码令牌的问题 - jwtHelper - ANGularjs
- php - httpd 工作成为僵尸进程
- javascript - Anime.js 使用画布添加相应的动画