无法在Python中打开html文件

2024-10-03 19:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图收集html文件中有多少个超链接。为此,我想阅读Python中的html文件并搜索所有的</a>锚点。但是,当我试图通过python传递html文件时,我会得到一个错误,该错误如下:

"UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1819: ordinal not in range(128)"

但是,如果我将相同的文本复制并粘贴到一个txt文件中,那么我的代码就可以工作了。我的代码如下:

def links(filename):
    infile = open(filename)
    content = infile.read()
    infile.close()
    anchorTagEnd = content.count("</a>")
    return anchorTagEnd

print(links("DePaul CDM - College of Computing and Digital Media.html"))

Tags: 文件代码inhtml错误asciilinkscontent
1条回答
网友
1楼 · 发布于 2024-10-03 19:22:09

为什么不使用HTML解析器来计算HTML文件中的链接数呢。在

使用^{}

from bs4 import BeautifulSoup

def links(filename):
    soup = BeautifulSoup(open(filename))
    return len(soup.find_all('a'))

print(links("DePaul CDM - College of Computing and Digital Media.html"))

使用^{}

^{pr2}$

相关问题 更多 >