0

私はjb hifiから特定の情報を抽出しようとしています.これが私がしたことです:

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)

re を使用して他の情報を削除しようとしました

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

しかし、うまくいきませんでした

だから私の問題は、無駄な情報を削除して「Apple ipod classic 160GB(black)」を取得するにはどうすればよいかということです

4

1 に答える 1

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) は 1 バイトではなく 2 バイトとして存在します。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パラメーターは、Latin 1 の代わりに UTF-8 を使用するよう BeautifulSoup に指示し、改行しないスペースが正しく削除されるようになりました。

于 2013-06-01T10:38:18.907 に答える