首页 > 解决方案 > 我已经编写了一个代码来查找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))

标签: pythonhtmlbeautifulsoup

解决方案


您必须提供字符串才能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

推荐阅读