2017-11-22 12 views
1

私は、複数のページの暗号解読値を繰り返し、開かれた、最高の、そして終値を返す、Pythonのbeautifulsoup4を使ってスクレイパープログラムを書きました。問題の掻き分け部分はうまくいきますが、すべての通貨を私のリストに保存することはできません。最後のものだけがリストに追加されます。複数のページをbeautifulsoupでリストにスクラップ

誰も私のすべてを保存する方法を教えてもらえますか?私は数時間の検索をしており、関連する回答を見つけることができないようです。コードは以下の通りである:

no_space = name_15.str.replace('\s+', '-') 

#lists out the pages to scrape 
for n in no_space: 
    page = 'https://coinmarketcap.com/currencies/' + n + '/historical-data/' 
    http = lib.PoolManager() 
    response = http.request('GET', page) 
    soup = BeautifulSoup(response.data, "lxml") 

    main_table = soup.find('tbody') 

    date=[] 
    open_p=[] 
    high_p=[] 
    low_p=[] 
    close_p=[] 

    table = [] 

    for row in main_table.find_all('td'): 
     table_pull = row.find_all_previous('td') #other find methods aren't returning what I need, but this works just fine 

    table = [p.text.strip() for p in table_pull] 

    date = table[208:1:-7] 
    open_p = table[207:1:-7] 
    high_p = table[206:1:-7] 
    low_p = table[205:1:-7] 
    close_p = table[204:0:-7] 

    df=pd.DataFrame(date,columns=['Date']) 
    df['Open']=list(map(float,open_p)) 
    df['High']=list(map(float,high_p)) 
    df['Low']=list(map(float,low_p)) 
    df['Close']=list(map(float,close_p)) 
    print(df) 
+0

forループでは、最後の行だけが処理されるようにあなたの 'table_pull'変数を上書きしています。 ( 'df [...] = list(...' lines)を代入するのではなく、データフレームに追加することを確実にするためにループの後にコードをインデントする必要があります。 – hoefling

+0

ありがとう@hoefling and @ rahlf23!それはそれらの面を書き直すためにもう少し手間がかかるだろうが、どこに間違っていたのか分かったのでかなり楽になるはずだ。 – mlt0882

答えて

0

単にあなたがすべての「TD」要素にアクセスして、不必要であるそのリストの前の要素にアクセスしようとしているように見える、置きます。また、@ hoeflingが指摘しているように、ループ内で変数を上書きし続けるのは、リストの最後の要素だけを返す理由です(つまり、ループの最後の反復のみで値が設定されます以前のものはすべて上書きされます)。申し訳ありませんが、私は現在、私のマシンのファイアウォールのためにこれをテストすることはできません。次のようにしてください:

no_space = name_15.str.replace('\s+', '-') 

#lists out the pages to scrape 
for n in no_space: 
    page = 'https://coinmarketcap.com/currencies/' + n + '/historical-data/' 
    http = lib.PoolManager() 
    response = http.request('GET', page) 
    soup = BeautifulSoup(response.data, "lxml") 

    main_table = soup.find('tbody') 

    table = [p.text.strip() for p in main_table.find_all('td')] 

    #You will need to re-think these indices here to get the info you want 
    date = table[208:1:-7] 
    open_p = table[207:1:-7] 
    high_p = table[206:1:-7] 
    low_p = table[205:1:-7] 
    close_p = table[204:0:-7] 

    df=pd.DataFrame(date,columns=['Date']) 
    df['Open']=list(map(float,open_p)) 
    df['High']=list(map(float,high_p)) 
    df['Low']=list(map(float,low_p)) 
    df['Close']=list(map(float,close_p)) 
    print(df) 
関連する問題