Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
本地html文件的Python打印源代码返回空格字符_Python_Html_Regex - Fatal编程技术网

本地html文件的Python打印源代码返回空格字符

本地html文件的Python打印源代码返回空格字符,python,html,regex,Python,Html,Regex,我有一个本地html文件,我想在源代码中读取和提取URL。然而,我的正则表达式总是返回空的,所以我试着打印源代码,并注意到所有字符都彼此隔开。你知道原因是什么吗 以下是我读取文件和正则表达式的代码: import re file=open("C:/Documents/name.html",'r') content=file.read() match = re.findall(r'<a href="(.*?)".*>(.*)</a>', content) print(mat

我有一个本地html文件,我想在源代码中读取和提取URL。然而,我的正则表达式总是返回空的,所以我试着打印源代码,并注意到所有字符都彼此隔开。你知道原因是什么吗

以下是我读取文件和正则表达式的代码:

import re
file=open("C:/Documents/name.html",'r')
content=file.read()
match = re.findall(r'<a href="(.*?)".*>(.*)</a>', content)
print(match)
重新导入
file=open(“C:/Documents/name.html”,“r”)
content=file.read()
match=re.findall(r'',内容)
打印(匹配)
当我尝试打印内容时,我得到:

< h t m l x m l n s : v = " u r n : s c h e m a s ...
编辑:多亏了abernert,这是一个编码问题,更正后的代码是:

import re
import codecs
file=codecs.open("C:/Users/140263/Documents/name.html",,encoding='utf-16-le')
content=file.read()
match = re.findall(r'<a href="(.*?)".*>(.*)</a>', content)
print(match)
重新导入
导入编解码器
file=codecs.open(“C:/Users/140263/Documents/name.html”,encoding='utf-16-le')
content=file.read()
match=re.findall(r'',内容)
打印(匹配)

问题在于,您的文件是以UTF-16-LE编码的,但您将其作为默认编码进行读取,而不是以UTF-16-LE编码

许多Windows软件使用UTF-16-LE作为文本文件的默认编码,这很烦人,但没有办法解决


UTF-16-LE将大多数字符存储为两个字节。对于像
这样的ASCII字符,请尝试
打印(repr(content))
这样我们可以看到该文件的实际字节数。另外,我猜您使用的是Python 2.7,但请确认您使用的是哪个版本。另外,请给我们一个实际正确的答案,这只会引发一个
AttributeError
,因为字符串没有
read
方法。我的猜测是这与UTF有关-16-LE编码,这是很多Windows程序都喜欢使用的。如果您将一堆大部分ASCII文本编码为UTF-16-LE,然后将其读取为字节,则得到的是ASCII字节与空字节交替。如果这确实是您的问题,并且您使用的是Python 2.x,那么解决方法是使用
io.open
codecs.op以文本文件的形式打开文件en
而不是
打开
,传递
encoding='utf-16-le
,然后用Unicode正则表达式(如
ur'
)搜索它。我使用的是Python 3.4是的,这就是编码问题。abarnert的建议奏效了!谢谢!
< h t m l … >
'<h\0t\0m\0l\0 … >\0'
file = open("C:/Documents/name.html", 'r', encoding='utf-16-le')