首页 > 解决方案 > PYTHON:ValueError:未知的网址类型:'comments_42.html'

问题描述

好的,所以我正在上 Pyhton 课程,作业要求我们从 html 文档中检索数据。这是我想出的:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl


ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

intlist = list()
tot = 0
count = 0
url = input('Enter - ')
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
tags = soup('span')
for tag in tags:
    n = tag.contents[0]
    n = int(n)
    count += 1
    tot = tot + n
print("Count:", n)
print("Total:", tot)

这就是我尝试访问文件时发生的情况(注意:我尝试检索的文件存储在本地):

回溯错误

这个错误的原因是什么?感谢任何人的帮助。

标签: pythonurlliburlopen

解决方案


您应该将 html 直接读入BeautifulSoup. 您无法使用urlopenas 轻松打开本地文件。

from bs4 import BeautifulSoup

...

with open('filename.html', 'r') as htmlfile:
    html = htmlfile.read()
soup = BeautifulSoup(html, 'html.parser')

现在它已加载供您解析,不要忘记更改filename.html为您的实际文件路径

编辑:您的代码还有更多问题。soup('span')找不到跨度元素。请参阅文档以获得至少基本的了解。


推荐阅读