html的空格和&nbsp怎么去除?

小白一个,在学爬虫。想爬51job的职业信息。但这个“公司性质:民营企业”和“公司规模:50-150人”好难爬。用xpath、正则、还有bs4都爬不下来。因为有空格在哪里,网上查了一下&nbsp也是一种空格(可能还有什么方法我没学到吧....)

我只有一个思路,把空格去了,然后就可以拿到文字了。可是我用了spilt()后,就得到了一个贼多内容的list。这个确实可以用list的快速匹配拿到文字。但我要爬100页,所以这个文字的位置都不同。所以我放弃了。求大神教教我。

html的片段:

 <p class="msg ltype">
                民营公司                            &nbsp;&nbsp;|&nbsp;&nbsp;50-150人                                        &nbsp;&nbsp;|&nbsp;&nbsp;电子技术/半导体/集成电路                        </p>

spilt()后获得的list:
[...'<p', 'class="msg', 'ltype">', '民营公司', '  |  50-150人', '  |  电子技术/半导体/集成电路',...]

list前后还有很多,用...代替吧

阅读 29.2k
6 个回答
var msg = $(".msg").text().replace(/&nbsp;/g, "").replace(/ /g, "").replace(/\s/g, "");
console.log(msg);
" &nbsp; 2323  2&nbsp;3 ".replace(/&nbsp;|\s/g, "")

用extract之类的方法能直接提取tag里的文字的吧,不管是用哪种框架。
然后在strip()下就好了。

同楼主,这个问题我也碰到了。

用html_parser好像不也行

clipboard.png
replace也不解决不完全,我希望把所有数据(房间类型,面积,位置,详细位置,发布时间,价格)放一行

clipboard.png
最后没办法只能这样了

import requests ##导入requests
from bs4 import BeautifulSoup ##导入bs4中的BeautifulSoup

res = requests.get('http://sz.58.com/nanshan/zufang/0/j2/?minprice=0_1600&PGTID=0d300008-0071-367d-7e8f-38bb92b6eebc&ClickID=2') 
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')

for info in soup.select('li'):
    a=info.select('.des .room')[0].text.replace(" ","")
    b=info.select('.des .add')[0].text.replace(" ","")
    c=info.select('.listliright .sendTime')[0].text.replace(" ","")
    d=info.select('.listliright .money')[0].text
    
    print(a,b,c,d)
    print(".....................................................")

clipboard.png

去掉nbsp硬空格,必须在unicode下替换才行

unicodeStr.replace(u'\xa0', '')
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题