2016-04-09 3 views
1

私はプログラミングとPythonを初めて使い、DCバイクシャアプログラムの所定の駅で利用可能なバイクの数にアクセスしようとしています。私はそれを行う最善の方法はBeautifulSoupと信じています。良いニュースは、データがここにクリーンなフォーマットと思われるものに利用可能であるということである。https://www.capitalbikeshare.com/data/stations/bikeStations.xmlDC bikeshareで使用可能なバイクにアクセスするには美しい

ここでは駅の例です:

<station> 
    <id>1</id> 
    <name>15th & S Eads St</name> 
    <terminalName>31000</terminalName> 
    <lastCommWithServer>1460217337648</lastCommWithServer> 
    <lat>38.858662</lat> 
    <long>-77.053199</long> 
    <installed>true</installed> 
    <locked>false</locked> 
    <installDate>0</installDate> 
    <removalDate/> 
    <temporary>false</temporary> 
    <public>true</public> 
    <nbBikes>7</nbBikes> 
    <nbEmptyDocks>8</nbEmptyDocks> 
    <latestUpdateTime>1460192501598</latestUpdateTime> 
</station> 

私は<nbBikes>価値を探しています。最初の5つのステーションの値を示すPythonスクリプトの開始と思っていたものを持っていました(これを一度取得すると、私が望むステーションを選択することに取り組みます)が、値は返されません。

# bikeShareParse.py - parses the capital bikeshare info page 


import bs4, requests 

url = "https://www.capitalbikeshare.com/data/stations/bikeStations.xml" 

res = requests.get(url) 
res.raise_for_status() 

#create the soup element from the file 
soup = bs4.BeautifulSoup("res.text", "lxml") 

# defines the part of the page we are looking for 
nbikes = soup.select('#text') 

#limits number of results for testing 
numOpen = 5 
for i in range(numOpen): 
     print nbikes 

私は私の問題は、(スタックオーバーフローの質問に正しくコードをフォーマットする方法を理解していないほか)nbikes = soup.select('#text')の値が間違っているということであると信じている:ここではスクリプトです。しかし、私は「#text」の値を得るために何かを置き換えることはできません。

私はこれに正しい方法で近づいていますか?もしそうなら、私は何が欠けていますか?

おかげ

+0

xml形式でデータを取得する場合は、xmletreeを使って試してみてください。 – bhansa

+0

ありがとう!私の問題の大きな部分は、BeautifulSoup for XMLを使用しようとしていたようです。私は基本的にこの新しいスクリプトを作成しようとしました: 'import xml.etree.ElementTree as ET tree = ET.ElementTree( 'https://www.capitalbikeshare.com/data/stations/bikeStations.xml') ルート= tree.getroot() print root' – mweinberg

+0

これはURLを返します。 'root1 = ET.fromstring( 'station')print root1'のような行で構造体を深くしようとすると、構文エラーが発生する – mweinberg

答えて

0

このスクリプトは、構造[station_ID、bikes_remaining]で辞書を作成します。 http://www.plotsofdots.com/archives/68

# from http://www.plotsofdots.com/archives/68 


import xml.etree.ElementTree as ET 
import urllib2 

#we parse the data using urlib2 and xml 
site='https://www.capitalbikeshare.com/data/stations/bikeStations.xml' 
htm=urllib2.urlopen(site) 
doc = ET.parse(htm) 

#we get the root tag 
root=doc.getroot() 
root.tag 

#we define empty lists for the empty bikes 
sID=[] 
embikes=[] 
#we now use a for loop to extract the information we are interested in 
for country in root.findall('station'): 
    sID.append(country.find('id').text) 
    embikes.append(int(country.find('nbBikes').text)) 

#this just tests that the process above works, can be commented out 
#print embikes 
#print sID 

#use zip to create touples and then parse them into a dataframe 
prov=zip(sID,embikes) 

print prov[0] 
+1

問題をソートしない限り、答えにはならない – hd1

関連する問題