Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.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
Python lxml.html解析和带请求的utf-8_Python_Html_Utf 8_Web Scraping_Lxml - Fatal编程技术网

Python lxml.html解析和带请求的utf-8

Python lxml.html解析和带请求的utf-8,python,html,utf-8,web-scraping,lxml,Python,Html,Utf 8,Web Scraping,Lxml,我使用请求检索包含一些unicode字符的url,并希望对其进行一些处理,然后将其写出 r=requests.get(url) f=open('unicode_test_1.html','w');f.write(r.content);f.close() html = lxml.html.fromstring(r.content) htmlOut = lxml.html.tostring(html) f=open('unicode_test_2.html','w');f.write(htmlOut

我使用请求检索包含一些unicode字符的url,并希望对其进行一些处理,然后将其写出

r=requests.get(url)
f=open('unicode_test_1.html','w');f.write(r.content);f.close()
html = lxml.html.fromstring(r.content)
htmlOut = lxml.html.tostring(html)
f=open('unicode_test_2.html','w');f.write(htmlOut);f.close()
在unicode_test_1.html中,所有字符看起来都很好,但在unicode_test_2.html中,一些字符变为乱码,这是为什么

然后我试着

html = lxml.html.fromstring(r.text)
htmlOut = lxml.html.tostring(html,encoding='latin1')
f=open('unicode_test_2.html','w');f.write(htmlOut);f.close()
它现在好像起作用了。但我不知道为什么会这样,总是用拉丁语?
r.text和r.content之间有什么区别,为什么我不能使用
encoding='utf-8'
写出html?

您没有指定是使用python 2还是3。根据使用的版本不同,编码的处理方式也不同。不管怎样,下面的建议或多或少是通用的

r.text和r.content的区别在于请求文档。Simply put请求将尝试为您找出字符编码,并在解码后返回Unicode。这是可以通过r.text访问的。要仅获取字节,请使用r.content

你真的需要掌握编码。阅读并观看以开始。另外,搜索“克服挫折:在python2中正确使用unicode”以获得更多帮助

只是澄清一下,它并不像总是使用一种编码而不是另一种编码那样简单。通过以字节为单位进行任何I/O来制作Unicode三明治,并在应用程序中使用Unicode。如果以字节(isinstance(mytext,str))开始,则需要知道解码为Unicode的编码,如果以Unicode(isinstance(mytext,Unicode))开始,则应编码为UTF-8,因为它将处理所有字符

确保你的编辑器、文件、服务器和数据库都配置为UTF-8,否则你会得到更多的“胡言乱语”


如果您需要更多帮助,请发布源文件和脚本输出。

您推荐的阅读/视频资源确实为我澄清了问题。谢谢