2013-06-01 38 views
0

我特林提取JB Hi-Fi spcify信息,這裏是我做過什麼:數據提取和重新

from BeautifulSoup import BeautifulSoup 
import urllib2 
import re 



url="http://www.jbhifionline.com.au/support.aspx?post=1&results=10&source=all&bnSearch=Go!&q=ipod&submit=Go" 

page=urllib2.urlopen(url) 
soup = BeautifulSoup(page.read()) 
Item0=soup.findAll('td',{'class':'check_title'})[0]  
print (Item0.renderContents()) 

輸出爲:

Apple iPod Classic 160GB (Black)  
<span class="SKU">MC297ZP/A</span> 

我要的是:

Apple iPod Classic 160GB (Black) 

,我試圖重新使用去除其他信息

print(Item0.renderContents()).replace{^<span:,""} 

,但它沒有工作

所以我的問題是我怎麼能去除無用信息,並獲得「蘋果iPod的經典160GB(黑色)」

回答

2

不要使用.renderContents();這是一個最好的調試工具。

剛拿到的第一個孩子:

>>> Item0.contents[0] 
u'Apple iPod Classic 160GB (Black)\xc2\xa0\r\n\t\t\t\t\t\t\t\t\t\t\t' 
>>> Item0.contents[0].strip() 
u'Apple iPod Classic 160GB (Black)\xc2' 

看來BeautifulSoup還沒有完全猜中的編碼,所以不換行空格(U + 00A0)存在以兩個字節而不是一個。它看起來像BeautifulSoup猜錯了:

>>> soup.originalEncoding 
'iso-8859-1' 

您可以通過使用響應標頭強制編碼;該服務器沒有設置字符集:

>>> page.info().getparam('charset') 
'utf-8' 
>>> page=urllib2.urlopen(url) 
>>> soup = BeautifulSoup(page.read(), fromEncoding=page.info().getparam('charset')) 
>>> Item0=soup.findAll('td',{'class':'check_title'})[0] 
>>> Item0.contents[0].strip() 
u'Apple iPod Classic 160GB (Black)' 

fromEncoding參數告訴BeautifulSoup使用UTF-8,而不是拉丁語1,現在的非換空間被正確地剝離。