2016-08-30 8 views
-1

私はあまりにもPythonには新しいですので、愚かな質問のために私を許してください。前もって感謝します。bs4からデータを保存して、利用可能な方法でリクエストしてください

I有しコードとBS4及び要求にプリントアウト次のデータ(フロート)、(印刷link.find_all( "ID")、link.text)

  • X
  • X bの
  • X C
  • Y
  • Y bの
  • Y C
  • Z
  • Z bの
  • ZのC

代わりに、私は好きそれを保存したいと思います:

  • X ABC
  • Y ABC
  • ZのABC

とそれをテキストファイルに保存して、後で使用することができます。

答えて

0

は、Pythonへようこそ(私ものpythonを使用してファイルにいくつかのデータを保存する方法がわからない)、ここではリスト秒の辞書を作成し、テキストファイルに書き込むの簡単な例です。

from bs4 import BeautifulSoup 
# import collections 

html_doc = """ 
<html><head><title>The Dormouse's story</title></head> 
<p class="story">Once upon a time there were three little sisters; and their names were 
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, 
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and 
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; 
<a href="http://example.com/tillie" class="sister" id="link3">Tillie2</a>; 
""" 

soup = BeautifulSoup(html_doc, 'html.parser') 
anchors = soup.find_all('a') 
data = {} # collections.OrderedDict() if order matters 

for item in anchors: 
    key = item.get('id') 
    if key not in data.keys(): 
     data.update({key: [item.text]}) 
    else: 
     values = data[key] 
     values.append(item.text) 
     data.update({key: values}) 

with open('example.txt', 'w') as f: 
    for key, value in data.items(): 
     line = key + ' ' + ' '.join(value) + '\n' 
     f.write(line) 

# example.txt 
# link1 Elsie 
# link3 Tillie Tillie2 
# link2 Lacie 
関連する問題