【问题标题】:Reading & Interacting With HTML Table Using Python使用 Python 阅读和交互 HTML 表格
【发布时间】:2017-01-11 02:09:17
【问题描述】:

我正在尝试从 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() 并尝试过使用 BeautifulSoup。尽管我对 BeautifulSoup 没有经验,但这些都不适合我。我的请求是否可行,或者网站是否保护了这些信息不被网络抓取?任何帮助将不胜感激!

【问题讨论】:

  • 您对特定于硒的方法感兴趣吗?
  • 是的!

标签: python html pandas beautifulsoup


【解决方案1】:

该页面非常动态(并且非常慢,至少在我这边),涉及 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 分钟(你可能需要在某个时候停止它) .

【讨论】:

【解决方案2】:

此页面由 JavaScript 渲染,如果您在浏览器中禁用 JS,此页面的输出为:

requests 或 pandas 只处理 HTML 代码。

【讨论】:

  • 我无法访问这些信息,因为它是用 JavaScript 呈现的吗?
  • @Evy555 是的,如果您想与浏览器交互,请使用 selenium。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 2023-03-28
  • 2021-01-04
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
  • 2017-05-04
相关资源
最近更新 更多