簡體   English   中英

使用beautifulsoup將多個頁面刮入列表

[英]Scraping multiple pages into list with beautifulsoup

我在Python中使用beautifulsoup4編寫了一個刮板程序,該程序對多頁加密貨幣值進行迭代,並返回開始值,最高值和結束值。 問題的抓取部分工作正常,但無法將其保存到我的列表中,只有最后一個添加到了列表中。

誰能幫我解決所有的問題? 我已經進行了數小時的搜索,但似乎找不到相關的答案。 代碼如下:

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)

簡而言之,看起來您正在訪問所有“ 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM