This article mainly introduces two solutions to Chinese garbled text in PythonBeautifulSoup. For more information, see
Solution 1:
Use BeautifulSoup of python to capture the webpage and output the webpage title, but the output is always garbled. after finding a solution for a long time, I will share it with you.
First, the code
The code is as follows:
From bs4 import BeautifulSoup
Import urllib2
Url = 'http: // www.jb51.net /'
Page = urllib2.urlopen (url)
Soup = BeautifulSoup (page, from_encoding = "utf8 ")
Print soup. original_encoding
Print (soup. title). encode ('gb18030 ')
File = open ("title.txt", "w ")
File. write (str (soup. title ))
File. close ()
For link in soup. find_all ('A '):
Print link ['href ']
At the beginning of the test, I found that although the output was garbled, it was normal to write it in the file. then I found a solution on the Internet.
Print the logic of an object: internally, it calls the object's _ str _ to obtain the corresponding string. here, it corresponds to the soup's _ str _, which is targeted at the soup itself, it is actually Unicode encoding, so you can specify the encoding when _ str _ is output as GBK to correctly display non-garbled Chinese characters.
For cmd: (in a Chinese system) it is encoded as GBK. Therefore, you only need to re-encode it as gb18030, and the output will be normal.
Is the following line of code
The code is as follows:
Print (soup. title). encode ('gb18030 ')
Solution 2:
When BeautifulSoup parses a UTF-8 webpage, if fromEncoding is not specified or fromEncoding is specified as UTF-8, Chinese garbled characters may occur.
To solve this problem, set the value of the fromEncoding parameter in the Beautifulsoup constructor to gb18030.
The code is as follows:
Import urllib2
From BeautifulSoup import BeautifulSoup
Page = urllib2.urlopen ('http: // www.jb51.net /');
Soup = BeautifulSoup (page, fromEncoding = "gb18030 ")
Print soup. originalEncoding
Print soup. pretloads ()