2017-11-28 13 views
0

特定の単語を検索している次のHTMLスクリプトがあります。Scrapy:HTMLテキストの検索文字による特定の単語の選択

<tbody> 
      <tr> 
       <th>Berufsbezeichnung:</th> 
       <td class="gray">ExampleName</td> 
      </tr> 
         <tr> 
       <th>Anrede:</th> 
       <td class="gray">Herrn</td> 
      </tr> 
         <tr> 
       <th>Name:</th> 
       <td class="gray">ExampleLastName</td> 
      </tr> 
         <tr> 
       <th>Vorname:</th> 
       <td class="gray">ExampleSurname</td> 
      </tr> 
      … 
</tbody> 

私は別の変数「Berufsbezeichnung」、「Anrede」、...正しい内容で満たされなければなら持っていると思います。例えば ​​"Berufsbezeichnung"のような同じデータセットでは、この変数は空のままでなければなりません。

私はありえない作業を、コンテンツを検索scrapyスクリプトを試してみましたが、それ:

soup = BeautifulSoup(response.css('table').extract()[0],'lxml') 

for elem in soup.findAll('tr'): 
    for eleme in elem.findAll('th'): 
     if eleme.get_text()=='Berufsbezeichnung:': 
      Berufsbezeichnung = elem.css('td.gray::text') 
     if eleme.get_text()=='Anrede:': 
      Anrede = elem.css('td.gray::text') 
     ... 

は、誰かがアイデアまたは多分も簡単な方法がありますか?

ありがとうございます!

+0

を - それは空の文字列(またはなしすることができ)。見つからない場合は、この変数に空の/デフォルトの文字列を設定します。 – furas

+2

あなたは 'scrapy'を使用していますか?はいの場合、あなたは本当にbsoupを必要としません – eLRuLL

答えて

0

この試してみてください。Berufsbezeichnung` `にデフォルト値を割り当てる開始時に

search_by_header = '//th[contains(., "{}")]/following-sibling::td/text()'.format 
Berufsbezeichnung = response..xpath(search_by_header("Berufsbezeichnung")).extract_first() 
Anrede = response.xpath(search_by_header("Anrede")).extract_first() 
+0

ありがとうございます!完璧に動作します! –

0

@eLRuLLコメントで指摘されているように、BeautifulSoupを使用する理由はまだありません。なぜなら、治療は既にpowerful tool availableです。あなたのケースでは

、私はあなたが単にxpathを使用することをお勧め:

extracted_values = {} # Store the extracted values in a dictionnary 

# Iterate on the tr node containted in the table node 
for tr_selector in response.selector.xpath('//table//tr'): 
    th_text = tr_selector.xpath('./th/text()').extract_first() 

    if th_text: # The th node contain text, read the text from the td node 
     extracted_values[th_text] = tr_selector.xpath('./td/text()').extract_first() 
+0

こんにちはクレメント、ありがとう!私はまだ治療とpythonに慣れようとしているので、私は非常に感謝しています! –

関連する問題