How python processes html Escape characters

Source: Internet
Author: User

How python processes html Escape characters

This document describes how to process html Escape characters in python. We will share this with you for your reference. The details are as follows:

Recently, when using Python to process webpage data, we often encounter html Escape characters (also called html character entities), such as <>. Character entities are generally used to indicate reserved characters in the web page, for example,> Use> to prevent the browser from being considered a tag. For details, refer to the HTML character entity of w3school. Although useful, they will greatly affect the parsing of webpage data. To process these escape characters, the following solutions are available:

1. Use HTMLParser for processing

import HTMLParserhtml_cont = " asdfg>123<"html_parser = HTMLParser.HTMLParser()new_cont = html_parser.unescape(html_cont)print new_cont #new_cont = " asdfg>123<"

Convert back (only space cannot be converted back ):

import cginew_cont = cgi.escape(new_cont)print new_cont #new_cont = " asdfg>123<"

2. directly replace one by one

html_cont = " asdfg>123<"new_cont = new_cont.replace(' ', ' ')print new_cont #new_cont = " asdfg>123<"new_cont = new_cont.replace('>', '>')print new_cont #new_cont = " asdfg>123<"new_cont = new_cont.replace('<', '<')print new_cont #new_cont = " asdfg>123<"

I don't know if there is any better way.

In addition, stackoverflow provides a solution for handling escape characters in xml: python-What's the best way to handle-like entities in XML documents ents with lxml? -Stack Overflow.

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.