2016-12-27 1 views
-1

私はPythonとBeautifulSoupの初心者です。私はWebスクレーパーを作ろうとしています。しかし、私はいくつかの問題に直面しており、方法を見つけることができません。ここに私の問題は、次のとおりです。BeauifulSoupを使用してデータを解析するには?

これは私がスクラップしたい場所からHTMLの一部です:

<tr> 
    <td class="num cell-icon-string" data-sort-value="6"> 
    <td class="cell-icon-string"><a class="ent-name" href="/pokedex/charizard" title="View pokedex for #006 Charizard">Charizard</a></td> 

</tr> 

<tr> 
    <td class="num cell-icon-string" data-sort-value="6"> 
    <td class="cell-icon-string"><a class="ent-name" href="/pokedex/charizard" title="View pokedex for #006 Charizard">Charizard</a><br> 
    <small class="aside">Mega Charizard X</small></td> 
</tr> 

、私は第一表の行から「リザードン」を抽出したいとの「メガリザードンX」 2行目。今、私は両方の行から "Charizard"を抽出することができます。ここで

は私のコードです:

#!/usr/bin/env python3 

from bs4 import BeautifulSoup 

soup = BeautifulSoup(open("data.html"), "lxml") 
poke_boxes = soup.findAll('a', attrs = {'class': 'ent-name'}) 

for poke_box in poke_boxes: 
    poke_name = poke_box.text.strip() 
     print(poke_name) 

答えて

-1

それはそのテキストをプリントアウトない場合は、そうでない場合はプリントアウトし、行を通過し、小さな要素が存在するかどうかを確認するためにあなたのロジックを変更する必要がありますアンカーテキストはあなたのようになります。中

soup = BeautifulSoup(html, 'lxml') 
trs = soup.findAll('tr') 
for tr in trs: 
    smalls = tr.findAll('small') 
    if smalls: 
     print(smalls[0].text) 
    else: 
     poke_box = tr.findAll('a') 
     print(poke_box[0].text) 
+0

ありがとうs!私はあなたのロジックを理解し、いくつかの回避策で、必要なものを実装することができました。 – torque

0
import bs4 
html = '''<tr> 
    <td class="num cell-icon-string" data-sort-value="6"> 
    <td class="cell-icon-string"><a class="ent-name" href="/pokedex/charizard" title="View pokedex for #006 Charizard">Charizard</a></td> 

</tr> 

<tr> 
    <td class="num cell-icon-string" data-sort-value="6"> 
    <td class="cell-icon-string"><a class="ent-name" href="/pokedex/charizard" title="View pokedex for #006 Charizard">Charizard</a><br> 
    <small class="aside">Mega Charizard X</small></td> 
</tr>''' 
soup = bs4.BeautifulSoup(html, 'lxml') 

[tr.get_text(strip=True) for tr in soup('tr')] 

アウト:

['Charizard', 'CharizardMega Charizard X'] 

あなたはstrip=Tureは、文字列内のすべてのスペースを削除します、タグ内のすべてのテキストを連結するget_text()を使用することができます

関連する問題