问题背景:
我有一个XML文件,我将它导入到BeautifulSoup中并通过它进行解析。一个节点具有以下功能:
<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>注意,该值在文本中包含
和
。我理解这是运输、返回和行提要的XML表示。
当我导入到BeautifulSoup中时,该值将转换为以下内容:
<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>您会注意到,
被转换为换行符。
我的用例要求该值保持原值。知道怎么才能让它留下来吗?还是把它改回来?
源代码:
python:(2.7.11)
from bs4 import BeautifulSoup #version 4.4.0
s = BeautifulSoup(open('test.xml'),'lxml-xml',from_encoding="ansi")
print s.DIAttribute
#XML file looks like
'''
<?xml version="1.0" encoding="UTF-8" ?>
<DIAttribute name="ObjectDesc" value="Line1
Line2
Line3"/>
'''Notepad++说源XML文件的编码是ANSI。
我尝试过的事情:
有人有什么想法吗?我感谢任何意见/建议。
发布于 2016-07-04 15:09:44
为了记录在案,首先没有正确处理
实体的库:BeautifulSoup(data ,convertEntities=BeautifulSoup.HTML_ENTITIES)、lxml.html.soupparser.unescape、xml.sax.saxutils.unescape
这就是工作原理(在Python2.x中):
import sys
import HTMLParser
## accept file name as argument, or read stdin if nothing passed
data = len(sys.argv) > 1 and open(sys.argv[1]).read() or sys.stdin.read()
parser = HTMLParser.HTMLParser()
print parser.unescape(data)https://stackoverflow.com/questions/35856699
复制相似问题