Python processing captures Chinese encoding and judgment encoding

Source: Internet
Author: User
During the development of self-use crawlers, some webpages are UTF-8, some are gb2312, and some are gbk. If no processing is added, all the collected webpages are garbled, the solution is to process html into a uniform UTF-8 during development and self-use Crawler. some webpages are UTF-8, some are gb2312, and some are gbk. If no processing is performed, all collected data is garbled, the solution is to process html into a unified UTF-8 encoding.

Python2.7

# Coding: utf-8import chardet # Capture Web htmlline = "http://www.pythontab.com" html_1 = urllib2.urlopen (line, timeout = 120 ). read () encoding_dict = chardet. detect (html_1) print encodingweb_encoding = encoding_dict ['encoding'] # for processing, the entire html will not be garbled. If web_encoding = 'utf-8' or web_encoding = 'utf-8': html = html_1else: html = html_1.decode ('gbk', 'ignore '). encode ('utf-8 ')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.