HTML转义字符&npsp;表示non-breaking space \xa0
1.参考
BeautifulSoupandUnicodeProblems
详细解释
unicodedata.normalize('NFKD',string)实际作用???
Scrapy:Selecttagwithnon-breakingspacewithxpath
>>>selector.xpath(u''' ...//p[normalize-space()] ...[not(contains(normalize-space(),"\u00a0"))]
normalize-space()实际作用???
In[244]:sel.css('.content')
Out[244]:[
BeautifulSoup下Unicode乱码解决
今天在用scrapy爬某个网站的数据,其中DOM解析我用的是BeautifulSoup,速度上没有XPath来得快,不过因为用了习惯了,所以一直用的bs,版本是bs4
不过在爬取过程中遇到了一些问题,其中一个是Unicode转码问题,这也算是python中一个著名问题了。
我遇到的算是BeautifulSoup中的一个奇葩bug吧,在网页中经常会有 这种标记,称为non-breakingspacecharacter,本来这个应该是忽略的,但在bs中会把这个符号
转义成为一个unicode编码\xa0,这就导致了后面如果要对内容处理的话会出现UnicodeError,特别是如果使用的是Console或者scrapy中写文件、写数据库的pipeline操作时,
出现无法转义的错误。
那么该如何解决呢,其实不难
s=u'\xa0'
s.replace(u'\xa0',u'')
之后就可以对s进行encode,比如:
s=u'\xa0'
s.replace(u'\xa0',u'').encode('utf-8')
特别是在我的项目中,如果需要把数据写到MongoDB中,这个bugfix完后,写数据立刻搞定,爬取的内容全部写到MongoDB中。
s.replace(u'\xa0',u'').encode('utf-8')
2.问题定位
https://en.wikipedia.org/wiki/Comparison_of_text_editors
定位元素显示为&npsp;
网页源代码表示为
memory =Limitedbyavailablememory No(64 KB) =Somelimitlessthanavailablememory(givemaxsizeifknown)
实际传输Hex为:
不间断空格的unicode表示为u\xa0',保存的时候编码utf-8则是'\xc2\xa0'
In[211]:fortrinresponse.xpath('//table[8]/tr[2]'):
...:print[u''.join(i.xpath('.//text()').extract())foriintr.xpath('./*')]
...:[u'memory',u'=Limitedbyavailablememory\xa0\xa0',u'No(64\xa0KB)',u'=Somelimitlessthanavailablememory(givemaxsizeifknown)']
In[212]:u'No(64\xa0KB)'.encode('utf-8')
Out[212]:'No(64\xc2\xa0KB)'In[213]:u'No(64\xa0KB)'.encode('utf-8').decode('utf-8')
Out[213]:u'No(64\xa0KB)'
保存csv直接使用excel打开会有乱码(默认ANSIgbk打开???,u'\xa0'超出gbk能够编码范围???),使用记事本或notepad++能够自动以utf-8正常打开。
使用记事本打开csv文件,另存为ANSI编码,之后excel正常打开。超出gbk编码范围的替换为'?'
3.如何处理
.extract_first().replace(u'\xa0',u'').strip().encode('utf-8','replace')
以上就是HTML转义字符&npsp;表示non-breakingspace\xa0的详细内容,更多关于HTML转义字符\xa0的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。