次のように簡略化された HTML ページを解析しようとしています。
<div class="anotherclass part"
<a href="http://example.com" >
<div class="column abc"><strike>£3.99</strike><br>£3.59</div>
<div class="column def"></div>
<div class="column ghi">1 Feb 2013</div>
<div class="column jkl">
<h4>A title</h4>
<p>
<img class="image" src="http://example.com/image.jpg">A, List, Of, Terms, To, Extract - 1 Feb 2013</p>
</div>
</a>
</div>
私はPythonのコーディングの初心者で、http://www.crummy.com/software/BeautifulSoup/bs3/documentation.htmlにあるbeautifulsoupのドキュメントを読んで再読しました。
私はこのコードを持っています:
from BeautifulSoup import BeautifulSoup
with open("file.html") as fp:
html = fp.read()
soup = BeautifulSoup(html)
parts = soup.findAll('a', attrs={"class":re.compile('part'), re.IGNORECASE} )
for part in parts:
mypart={}
# ghi
mypart['ghi'] = part.find(attrs={"class": re.compile('ghi')} ).string
# def
mypart['def'] = part.find(attrs={"class": re.compile('def')} ).string
# h4
mypart['title'] = part.find('h4').string
# jkl
mypart['other'] = part.find('p').string
# abc
pattern = re.compile( r'\&\#163\;(\d{1,}\.?\d{2}?)' )
theprices = re.findall( pattern, str(part) )
if len(theprices) == 2:
mypart['price'] = theprices[1]
mypart['rrp'] = theprices[0]
elif len(theprices) == 1:
mypart['price'] = theprices[0]
mypart['rrp'] = theprices[0]
else:
mypart['price'] = None
mypart['rrp'] = None
クラスからテキストを抽出したいのですが、スクリプトが正しく機能するdef
とghi
思います。
abc
また、スクリプトが現時点でややぎこちない方法で行っている2 つの価格も抽出したいと考えています。この部分には 2 つの価格がある場合もあれば、1 つの場合とない場合もあります。
最後に、スクリプトが失敗する"A, List, Of, Terms, To, Extract"
クラスから部分を抽出したいと思います。jkl
タグの文字列部分を取得するとうまくいくと思いましたが、p
なぜうまくいかないのかわかりません。この部分の日付は常にクラスの日付と一致するghi
ため、簡単に交換/削除できます。
何かアドバイス?ありがとうございました!