使用Python读取HTML表并与之交互

2024-04-26 18:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从一个HTML表中获取信息,该表具有在不同时间段中筛选的交互能力。示例表位于以下URL:http://quotes.freerealtime.com/dl/frt/M?IM=quotes&type=Time%26Sales&SA=quotes&symbol=IBM&qm_page=45750。在

我想从9:30开始,然后向前跳1分钟与表交互,我想将所有数据导出到一个DataFrame。 我试过用pandas.read_html()也尝试过使用beauthoulsoup。这两种方法都不适合我,尽管我对Beautulsoup缺乏经验。我的请求是可能的还是网站已经保护了这些信息,使其不被网站废弃?任何帮助都将不胜感激!在


Tags: comhttpurl示例网站htmltypesa
2条回答

此页面由JavaScript呈现,如果在浏览器中禁用JS,则此页面的输出为:

enter image description here

请求或pandas只处理HTML代码。在

这个页面非常动态(而且非常慢,至少在我这边是这样),包括JavaScript和多个异步请求来获取数据。用requests来实现这一点并不容易,您可能需要通过selenium使用浏览器自动化。在

这里有一些东西让你开始。注意Explicit Waits的用法:

import pandas as pd
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


driver = webdriver.Firefox()
driver.maximize_window()
driver.get("http://quotes.freerealtime.com/dl/frt/M?IM=quotes&type=Time%26Sales&SA=quotes&symbol=IBM&qm_page=45750")

wait = WebDriverWait(driver, 400)  # 400 seconds timeout

# wait for select element to be visible
time_select = Select(wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "select[name=time]"))))

# select 9:30 and go
time_select.select_by_visible_text("09:30")
driver.execute_script("arguments[0].click();", driver.find_element_by_id("go"))
time.sleep(2)

while True:
    # wait for the table to appear and load to pandas dataframe
    table = wait.until(EC.presence_of_element_located((By.ID, "qmmt-time-and-sales-data-table")))
    df = pd.read_html(table.get_attribute("outerHTML"))
    print(df[0])

    # wait for offset select to be visible and forward it 1 min
    offset_select = Select(wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "select[name=timeOffset]"))))
    offset_select.select_by_value("1")

    time.sleep(2)

    # TODO: think of a break condition

请注意,这在我的机器上运行得非常非常慢,我不确定它在你的机器上运行得有多好,但它一直在无休止的循环中向前推进1分钟(您可能需要在某个时刻停止它)。在

相关问题 更多 >