【问题标题】:How to scrape an updating HTML table using Selenium?如何使用 Selenium 抓取更新的 HTML 表?
【发布时间】:2021-06-15 13:55:44
【问题描述】:

我希望从link 中刮取硬币表并按日期创建一个 CSV 文件。对于每次新硬币更新,都应在现有数据文件的顶部创建一个新条目。

期望的输出

Coin,Pings,...Datetime

BTC,25,...07:17:05 03/18/21

我还没有走多远,但下面是我的尝试

from selenium import webdriver
import numpy as np
import pandas as pd

firefox = webdriver.Firefox(executable_path="/usr/local/bin/geckodriver")
firefox.get('https://agile-cliffs-23967.herokuapp.com/binance/')

rows = len(firefox.find_elements_by_xpath("/html/body/div/section[2]/div/div/div/div/table/tr"))
columns = len(firefox.find_elements_by_xpath("/html/body/div/section[2]/div/div/div/div/table/tr[1]/th"))

df = pd.DataFrame(columns=['Coin','Pings','Net Vol BTC','Net Vol per','Recent Total Vol BTC', 'Recent Vol per', 'Recent Net Vol', 'Datetime'])

for r in range(1, rows+1):
    for c in range(1, columns+1): 
        value = firefox.find_element_by_xpath("/html/body/div/section[2]/div/div/div/div/table/tr["+str(r)+"]/th["+str(c)+"]").text
        print(value)
        
#         df.loc[i, ['Coin']] = 

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping geckodriver


    【解决方案1】:

    由于数据是动态加载的,您可以直接从源中检索它,不需要Selenium。它将返回带有带有|-delimited 值的行的json,这些行需要拆分并且可以附加到DataFrame。由于站点每分钟更新一次,您可以将所有内容包装在 while True 中,以使代码运行 every 60 seconds

    import requests
    import time
    import json
    
    headers = ['Coin','Pings','Net Vol BTC','Net Vol %','Recent Total Vol BTC', 'Recent Vol %', 'Recent Net Vol', 'Datetime (UTC)']
    df = pd.DataFrame(columns=headers)
    
    s = requests.Session()
    starttime = time.time()
    
    while True:
        response = s.get('https://agile-cliffs-23967.herokuapp.com/ok', headers={'Connection': 'keep-alive'})
        d = json.loads(response.text)
        rows = [str(i).split('|') for i in d['resu'][:-1]]
        if rows:
            data = [dict(zip(headers, l)) for l in rows]
            df = df.append(data, ignore_index=True)
            df.to_csv('filename.csv', index=False)
        time.sleep(60.0 - ((time.time() - starttime) % 60.0))
    

    【讨论】:

    • 谢谢。正是我想要的!
    • 不客气。请注意,当您重新运行代码时,csv 将被覆盖。如果您想继续使用现有的 csv 文件,您可以在代码开头使用 df = pd.read_csv('filename.csv') 加载它
    【解决方案2】:

    您可以通过将行数据放入字典来将行数据附加到 DataFrame:

    # We reuse the headers when building dicts below
    headers = ['Coin','Pings','Net Vol BTC','Net Vol per','Recent Total Vol BTC', 'Recent Vol per', 'Recent Net Vol', 'Datetime']
    df = pd.DataFrame(columns=headers)
    
    for r in range(1, rows+1):
        data = [firefox.find_element_by_xpath("/html/body/div/section[2]/div/div/div/div/table/tr["+str(r)+"]/th["+str(c)+"]").text \
                    for c in range(1, columns+1)]
        row_dict = dict(zip(headers, data))
        df = df.append(row_dict, ignore_index=True)
    

    【讨论】:

    • 感谢您提供有用的解决方案。
    • 没问题。由于您是 StackOverflow (SO) 的新手,请查看 this page 以了解 SO 的做事方式。特别是,如果这解决了您的问题,您可能会考虑接受 @RJ Adriaansen 的回答。
    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多