2017-01-17 6 views
0

私の出身(OとD)をこのウェブサイト(http://fahrplan.sbb.ch/bin/query.exe/en)のフォームに入力して、結果をcsvファイルに書きたいとします。入力する場所の数が1000に近いので、このタスクを自動化する方法は私が唯一の選択肢です。hereから変更した以下のコードを使用して、フォームに入力場所を入力して結果を画面に印刷できますbr.response().read()。しかし結果はhtml形式で表示されますが、下の画像で青色で強調表示された部分をcsvファイルにエクスポートします。どうやってやるの?ウェブサイトの出力フォームの選択部分をPythonでCSVに保存

画像:

see image below

マイコード:

from mechanize import Browser 
br = Browser() 

# Ignore robots.txt 
br.set_handle_robots(False) 
# Google demands a user-agent that isn't a robot 
br.addheaders = [('User-agent', 'Chrome')] 

# Retrieve the Google home page, saving the response 
br.open('http://fahrplan.sbb.ch/bin/query.exe/en') 

# # Show the available forms 
# counter = 0 
# for f in br.forms(): 
#  counter += 1 
#  print f, counter 
# print 'counter', counter 

# Enter the text inpur 
br.select_form(nr=6) 
br.form[ "REQ0JourneyStopsS0G" ] = 'Leverkusen Mitte' 
br.form[ "REQ0JourneyStopsZ0G" ] = 'Pescara Centrale' 


# Get the search results 
br.submit() 
print br.response().read() 


# How can I export the result to csv??? 

答えて

0

は、GoogleのChromeのソースコンソールで結果のHTMLページのソースを見れば、あなたは見つけるでしょう4つの結果。ここでは最初の結果の出発部分のキャプチャです:

result item

あなたは私のキャプチャに黄色で強調表示されたテキストを使用してコンソールを検索することにより、残りの結果を得ることができます。必要なのは、Beautiful Soupを使用してこのHTMLコードを削り取り、スライスしたセクションをCSVファイルに保存するだけです。

0

別の回答で述べたように、BeautifulSoupなどのHTMLパーサーを使用して応答を解析し、必要な値をカンマ区切りの文字列で入力してファイルに書き込むことができます。ここで

はあなたのより良いアイデアを与えるためのサンプルコードです:

from mechanize import Browser 
from bs4 import BeautifulSoup 

# get the response from mechanize Browser 

soup = BeautifulSoup(response, 'html.parser') 
trs = soup.select('table.hfs_overview tr') 
with open('out.csv', 'a+') as f: 
    for tr in trs: 
     locations = tr.select('td.location.departure a') 
     if len(locations) > 0: 
      location = locations[0].contents[0].strip() 
      prefix = tr.select('td.prefix')[0].contents[0].strip() 
      time = tr.select('td.time')[0].contents[0].strip() 
      # parse more values here 
      # write to file 
      f.write("{},{},{}\n".format(location, prefix, time)) 
関連する問題