473,416 Members | 1,562 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

BeautifulSoup vs. loose & chars

I've been parsing existing HTML with BeautifulSoup, and occasionally
hit content which has something like "Design & Advertising", that is,
an "&" instead of an "&". Is there some way I can get BeautifulSoup
to clean those up? There are various parsing options related to "&"
handling, but none of them seem to do quite the right thing.

If I write the BeautifulSoup parse tree back out with "prettify",
the loose "&" is still in there. So the output is
rejected by XML parsers. Which is why this is a problem.
I need valid XML out, even if what went in wasn't quite valid.

John Nagle
Dec 26 '06 #1
7 4581

John Nagle wrote:
I've been parsing existing HTML with BeautifulSoup, and occasionally
hit content which has something like "Design & Advertising", that is,
an "&" instead of an "&". Is there some way I can get BeautifulSoup
to clean those up? There are various parsing options related to "&"
handling, but none of them seem to do quite the right thing.

If I write the BeautifulSoup parse tree back out with "prettify",
the loose "&" is still in there. So the output is
rejected by XML parsers. Which is why this is a problem.
I need valid XML out, even if what went in wasn't quite valid.

John Nagle

So do you want to remove "&" or replace them with "&" ? If you want
to replace it try the following;

import urllib, sys

try:
location = urllib.urlopen(url)
except IOError, (errno, strerror):
sys.exit("I/O error(%s): %s" % (errno, strerror))

content = location.read()
content = content.replace("&", "&")
To do this with BeautifulSoup, i think you need to go through every
Tag, get its content, see if it contains an "&" and then replace the
Tag with the same Tag but the content contains "&"

Hope this helps.
Cheers

Dec 26 '06 #2
On 26 Dec 2006 04:22:38 -0800, placid <Bu****@gmail.comwrote:
So do you want to remove "&" or replace them with "&amp;" ? If you want
to replace it try the following;
I think he wants to replace them, but just the invalid ones. I.e.,

This & this &amp; that

would become

This &amp; this &amp; that
No, i don't know how to do this efficiently. =/...
I think some kind of regex could do it.

--
Felipe.
Dec 26 '06 #3
"Felipe Almeida Lessa" <fe**********@gmail.comwrote:
On 26 Dec 2006 04:22:38 -0800, placid <Bu****@gmail.comwrote:
>So do you want to remove "&" or replace them with "&amp;" ? If you
want to replace it try the following;

I think he wants to replace them, but just the invalid ones. I.e.,

This & this &amp; that

would become

This &amp; this &amp; that
No, i don't know how to do this efficiently. =/...
I think some kind of regex could do it.
Since he's asking for valid xml as output, it isn't sufficient just to
ignore entity definitions: HTML has a lot of named entities such as
&nbsp; but xml only has a very limited set of predefined named entities.
The safest technique is to convert them all to numeric escapes except
for the very limited set also guaranteed to be available in xml.

Try this:

from cgi import escape
import re
from htmlentitydefs import name2codepoint
name2codepoint = name2codepoint.copy()
name2codepoint['apos']=ord("'")

EntityPattern =
re.compile('&(?:#(\d+)|(?:#x([\da-fA-F]+))|([a-zA-Z]+));')

def decodeEntities(s, encoding='utf-8'):
def unescape(match):
code = match.group(1)
if code:
return unichr(int(code, 10))
else:
code = match.group(2)
if code:
return unichr(int(code, 16))
else:
return unichr(name2codepoint[match.group(3)])
return EntityPattern.sub(unescape, s)
>>escape(
decodeEntities("This & this &amp; that&nbsp;&eacute;")).encode(
'ascii', 'xmlcharrefreplace')
'This &amp; this &amp; that é'
P.S. apos is handled specially as it isn't technically a
valid html entity (and Python doesn't include it in its entity
list), but it is an xml entity and recognised by many browsers so some
people might use it in html.

Dec 26 '06 #4
Felipe Almeida Lessa wrote:
On 26 Dec 2006 04:22:38 -0800, placid <Bu****@gmail.comwrote:
>So do you want to remove "&" or replace them with "&amp;" ? If you want
to replace it try the following;


I think he wants to replace them, but just the invalid ones. I.e.,

This & this &amp; that

would become

This &amp; this &amp; that
No, i don't know how to do this efficiently. =/...
I think some kind of regex could do it.
Yes, and the appropriate one is:

krefindamp = re.compile(r'&(?!(\w|#)+;)')
...
xmlsection = re.sub(krefindamp,'&amp;',xmlsection)

This will replace an '&' with '&amp' if the '&' isn't
immediately followed by some combination of letters, numbers,
and '#' ending with a ';' Admittedly this would let something
like '&xx#2;', which isn't a legal entity, through unmodified.

There's still a potential problem with unknown entities in the output XML, but
at least they're recognized as entities.

John Nagle
Dec 26 '06 #5


Duncan Booth skrev:
"Felipe Almeida Lessa" <fe**********@gmail.comwrote:

>On 26 Dec 2006 04:22:38 -0800, placid <Bu****@gmail.comwrote:
>>So do you want to remove "&" or replace them with "&amp;" ? If you
want to replace it try the following;
I think he wants to replace them, but just the invalid ones. I.e.,

This & this &amp; that

would become

This &amp; this &amp; that
No, i don't know how to do this efficiently. =/...
I think some kind of regex could do it.


Since he's asking for valid xml as output, it isn't sufficient just to
ignore entity definitions: HTML has a lot of named entities such as
&nbsp; but xml only has a very limited set of predefined named entities.
The safest technique is to convert them all to numeric escapes except
for the very limited set also guaranteed to be available in xml.

Try this:

from cgi import escape
import re
from htmlentitydefs import name2codepoint
name2codepoint = name2codepoint.copy()
name2codepoint['apos']=ord("'")

EntityPattern =
re.compile('&(?:#(\d+)|(?:#x([\da-fA-F]+))|([a-zA-Z]+));')

def decodeEntities(s, encoding='utf-8'):
def unescape(match):
code = match.group(1)
if code:
return unichr(int(code, 10))
else:
code = match.group(2)
if code:
return unichr(int(code, 16))
else:
return unichr(name2codepoint[match.group(3)])
return EntityPattern.sub(unescape, s)

>>>escape(
decodeEntities("This & this &amp; that&nbsp;&eacute;")).encode(
'ascii', 'xmlcharrefreplace')
'This &amp; this &amp; that é'
P.S. apos is handled specially as it isn't technically a
valid html entity (and Python doesn't include it in its entity
list), but it is an xml entity and recognised by many browsers so some
people might use it in html.
Hey i fund this site:
http://www.htmlhelp.com/reference/ht...s/symbols.html

I hope that its what you mean.

/Scripter47

Dec 26 '06 #6
Andreas Lysdal <an*****@riddergarn.dkwrote:
>P.S. apos is handled specially as it isn't technically a
valid html entity (and Python doesn't include it in its entity
list), but it is an xml entity and recognised by many browsers so some
people might use it in html.
Hey i fund this site:
http://www.htmlhelp.com/reference/ht...s/symbols.html

I hope that its what you mean.
Try
http://www.w3.org/TR/html4/sgml/entities.html#entities
for a more complete list.
Dec 26 '06 #7
John Nagle wrote:
Felipe Almeida Lessa wrote:
>On 26 Dec 2006 04:22:38 -0800, placid <Bu****@gmail.comwrote:

>>So do you want to remove "&" or replace them with "&amp;" ? If you want
to replace it try the following;
I think he wants to replace them, but just the invalid ones. I.e.,

This & this &amp; that

would become

This &amp; this &amp; that
No, i don't know how to do this efficiently. =/...
I think some kind of regex could do it.

Yes, and the appropriate one is:

krefindamp = re.compile(r'&(?!(\w|#)+;)')
...
xmlsection = re.sub(krefindamp,'&amp;',xmlsection)

This will replace an '&' with '&amp' if the '&' isn't
immediately followed by some combination of letters, numbers,
and '#' ending with a ';' Admittedly this would let something
like '&xx#2;', which isn't a legal entity, through unmodified.

There's still a potential problem with unknown entities in the output XML, but
at least they're recognized as entities.

John Nagle
Here's another idea:
>>s = '''<htmlhtm tag should not translate
& should be &amp;
&xx#2; isn't a legal entity and should translate
{ is a legal entity and should not translate
</html>
>>import SE # http://cheeseshop.python.org/pypi/SE/2.3
HTM_Escapes = SE.SE (definitions) # See definitions below the
dotted line
>>print HTM_Escapes (s)
<htmlhtm tag should not translate
&gt; &amp; should be &amp;
&gt; &amp;xx#2; isn&quot;t a legal entity and should translate
&gt; { is a legal entity and should not translate
</html>

Regards

Frederic
------------------------------------------------------------------------------
definitions = '''

# Do # Don't do
# " =&nbsp;" &nbsp;== # 32 20
(34)=&dquot; &dquot;== # 34 22
&=&amp; &amp;== # 38 26
'=&quot; &quot;== # 39 27
<=&lt; &lt;== # 60 3c
>=&gt; &gt;== # 62 3e
©=&copy; &copy;== # 169 a9
·=&middot; &middot;== # 183 b7
»=&raquo; &raquo;== # 187 bb
À=&Agrave; &Agrave;== # 192 c0
Á=&Aacute; &Aacute;== # 193 c1
Â=&Acirc; &Acirc;== # 194 c2
Ã=&Atilde; &Atilde;== # 195 c3
Ä=&Auml; &Auml;== # 196 c4
Å=&Aring; &Aring;== # 197 c5
Æ=&AElig; &AElig;== # 198 c6
Ç=&Ccedil; &Ccedil;== # 199 c7
È=&Egrave; &Egrave;== # 200 c8
É=&Eacute; &Eacute;== # 201 c9
Ê=&Ecirc; &Ecirc;== # 202 ca
Ë=&Euml; &Euml;== # 203 cb
Ì=&Igrave; &Igrave;== # 204 cc
Í=&Iacute; &Iacute;== # 205 cd
Î=&Icirc; &Icirc;== # 206 ce
Ï=&Iuml; &Iuml;== # 207 cf
Ð=&Eth; &Eth;== # 208 d0
Ñ=&Ntilde; &Ntilde;== # 209 d1
Ò=&Ograve; &Ograve;== # 210 d2
Ó=&Oacute; &Oacute;== # 211 d3
Ô=&Ocirc; &Ocirc;== # 212 d4
Õ=&Otilde; &Otilde;== # 213 d5
Ö=&Ouml; &Ouml;== # 214 d6
Ø=&Oslash; &Oslash;== # 216 d8
Ù=&Ugrve; &Ugrve;== # 217 d9
Ú=&Uacute; &Uacute;== # 218 da
Û=&Ucirc; &Ucirc;== # 219 db
Ü=&Uuml; &Uuml;== # 220 dc
Ý=&Yacute; &Yacute;== # 221 dd
Þ=&Thorn; &Thorn;== # 222 de
ß=&szlig; &szlig;== # 223 df
à=&agrave; &agrave;== # 224 e0
á=&aacute; &aacute;== # 225 e1
â=&acirc; &acirc;== # 226 e2
ã=&atilde; &atilde;== # 227 e3
ä=&auml; &auml;== # 228 e4
å=&aring; &aring;== # 229 e5
æ=&aelig; &aelig;== # 230 e6
ç=&ccedil; &ccedil;== # 231 e7
è=&egrave; &egrave;== # 232 e8
é=&eacute; &eacute;== # 233 e9
ê=&ecirc; &ecirc;== # 234 ea
ë=&euml; &euml;== # 235 eb
ì=&igrave; &igrave;== # 236 ec
í=&iacute; &iacute;== # 237 ed
î=&icirc; &icirc;== # 238 ee
ï=&iuml; &iuml;== # 239 ef
ð=&eth; &eth;== # 240 f0
ñ=&ntilde; &ntilde;== # 241 f1
ò=&ograve; &ograve;== # 242 f2
ó=&oacute; &oacute;== # 243 f3
ô=&ocric; &ocric;== # 244 f4
õ=&otilde; &otilde;== # 245 f5
ö=&ouml; &ouml;== # 246 f6
ø=&oslash; &oslash;== # 248 f8
ù=&ugrave; &ugrave;== # 249 f9
ú=&uacute; &uacute;== # 250 fa
û=&ucirc; &ucirc;== # 251 fb
ü=&uuml; &uuml;== # 252 fc
ý=&yacute; &yacute;== # 253 fd
þ=&thorn; &thorn;== # 254 fe
(xff)=ÿ # 255 ff
&#== # All numeric codes
"~<(.|\n)*?>~==" # All HTM tags '''

If the ampersand is all you need to handle you can erase the others
in the first column. You need to keep the second column though, except
the last entry, because the tags don't need protection if '<' and
'>' in the first column are gone.
Definitions are easily edited and can be kept in text files.
The SE constructor accepts a file name instead of a definitions string:
>>HTM_Escapes = SE.SE ('definition_file_name')

-------------------------------------------------------------------

Dec 26 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Steve Young | last post by:
I tried using BeautifulSoup to make changes to the url links on html pages, but when the page was displayed, it was garbled up and didn't look right (even when I didn't actually change anything on...
7
by: Gonzillaaa | last post by:
I'm trying to get the data on the "Central London Property Price Guide" box at the left hand side of this page http://www.findaproperty.com/regi0018.html I have managed to get the data :) but...
4
by: William Xu | last post by:
Hi, all, This piece of code used to work well. i guess the error occurs after some upgrade. >>> import urllib >>> from BeautifulSoup import BeautifulSoup >>> url = 'http://www.google.com'...
5
by: John Nagle | last post by:
This, which is from a real web site, went into BeautifulSoup: <param name="movie" value="/images/offersBanners/sw04.swf?binfot=We offer fantastic rates for selected weeks or days!!&blinkt=Click...
9
by: Mizipzor | last post by:
Is there a way to "subscribe" to individual topics? im currently getting bombarded with daily digests and i wish to only receive a mail when there is activity in a topic that interests me. Can this...
6
by: John Nagle | last post by:
Here's a construct with which BeautifulSoup has problems. It's from "http://support.microsoft.com/contactussupport/?ws=support". This is the original: <a...
5
by: Larry Bates | last post by:
Info: Python version: ActivePython 2.5.1.1 Platform: Windows I wanted to install BeautifulSoup today for a small project and decided to use easy_install. I can install other packages just...
3
by: Magnus.Moraberg | last post by:
Hi, I wish to extract all the words on a set of webpages and store them in a large dictionary. I then wish to procuce a list with the most common words for the language under consideration. So,...
3
by: bsagert | last post by:
I downloaded BeautifulSoup.py from http://www.crummy.com/software/BeautifulSoup/ and being a n00bie, I just placed it in my Windows c:\python25\lib\ file. When I type "import beautifulsoup" from...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.