python - 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)
这就是我尝试访问文件时发生的情况(注意:我尝试检索的文件存储在本地):
这个错误的原因是什么?感谢任何人的帮助。
解决方案
您应该将 html 直接读入BeautifulSoup
. 您无法使用urlopen
as 轻松打开本地文件。
from bs4 import BeautifulSoup
...
with open('filename.html', 'r') as htmlfile:
html = htmlfile.read()
soup = BeautifulSoup(html, 'html.parser')
现在它已加载供您解析,不要忘记更改filename.html
为您的实际文件路径
编辑:您的代码还有更多问题。soup('span')
找不到跨度元素。请参阅文档以获得至少基本的了解。
推荐阅读
- json - Swift JSOn 解码错误:预期解码数组
但找到了一本字典 - python - python中的json编码dict和golang中的map不匹配
- git - Git 要求我提交数百个文件,而我只更改了其中的 2 个
- python-sphinx - Sphinx 的 Rinohtype 前端:如何操作 PDF 字幕,默认为“发布”
- git - 无法使用 intellij 从 GitHub 连接和克隆项目
- bash - 我有办法简化这些回声吗?
- python - 如何使用 matplotlib 子图为每一行绘制折线图?
- homebrew - Kibana 还没有准备好 - 好的啊,为什么?
- java - How do I install a SQL Server Java driver into a linux docker container?
- python - 从脚本设置 python 环境的问题