Chinese output
#-*-coding:utf8-*-ImportRequestsImportRetimeout= 8Headers= {'user-agent':'mozilla/5.0 (Windows NT 6.3; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/41.0.2272.118 safari/537.36'}defBanner (URL):Try: HTML= Requests.get (url,headers=headers,timeout=timeout) html.encoding='Utf-8' #this line is to convert the encoding to utf-8 otherwise the Chinese will show garbled. Banner= Re.findall (r'<title> (. *?) </title>', Html.text)returnBanner[0]exceptexception,e:Printereturn "No"if __name__=="__main__": PrintBanner'http://www.baidu.com')
Write Unicode to text
One:
>>> f = open ('1.txt','W')>>> f.write (U'Fork Fork') Traceback (most recent): File"<stdin>", Line 1,inch<module>Unicodeencodeerror:'ASCII'Codec can'T encode characters in position 0-1: OrdinAl not inchRange (128)>>> a = Unicode.encode (u'Fork Fork','Utf-8')>>>F.write (a)>>> F.close ()
Two:
>>>ImportCodecs>>> f = Codecs.open ('1.txt','W')>>> f.write (U'Fork Fork') Traceback (most recent): File"<stdin>", Line 1,inch<module>Unicodeencodeerror:'ASCII'Codec can'T encode characters in position 0-1: OrdinAl not inchRange (128)>>> f = Codecs.open ('1.txt','W','Utf-8')>>> f.write (U'Fork Fork')>>> F.close ()
Python Chinese output and write text