2017-01-25 10 views
1

私はBeautifulSoupを使ってTableau twb XMLファイルを解析し、レポート内のワークシートのリストを取得しています。BeautifulSoup xmlクラス名の値を取得

私が探しています値を保持しているXMLが

クラス=「ワークシート」のすべてを取得し、その後、私は "を取得したいそれらの例から名前値を取得する方法に苦しん
<window class='worksheet' name='ML Productivity'> 

ですMLの生産性 '値。

コード私はこれまでのところ以下のとおりです。

import sys, os 
import bs4 as bs 

twbpath = "C:/tbw tbwx files/" 

outpath = "C:/out/" 

outFile = open(outpath + 'output.txt', "w") 
#twbList = open(outpath + 'twb.txt', "w") 

for subdir, dirs, files in os.walk(twbpath): 
    for file in files: 
     if file.endswith('.twb'): 
      print(subdir.replace(twbpath,'') + '-' + file) 
      filepath = open(subdir + '/' + file, encoding='utf-8').read()   
      soup = bs.BeautifulSoup(filepath, 'xml') 
      classnodes = soup.findAll('window') 

      for classnode in classnodes: 
       if str(classnode) == 'worksheet': 
        outFile.writelines(file + ',' + str(classnode) + '\n') 
        print(subdir.replace(twbpath,'') + '-' + file, classnode) 

outFile.close() 

答えて

1

あなたが必要な属性を取得するためにclass属性値が希望window要素をフィルタリングして、treat the result like a dictionaryことができます。

find_all()を使用し、あなたが検索する必要があり、複数の window要素がある場合

soup.find('window', {'class': 'worksheet'})['name'] 

for window in soup.find_all('window', {'class': 'worksheet'}): 
    print(window['name']) 
関連する問題