【问题标题】:How to use Pandas read_html and requests library to read the table?如何使用 Pandas read_html 和 requests 库来读取表格?
【发布时间】:2013-11-27 19:16:18
【问题描述】:

我如何在以下位置获取基金的价格:

http://www.prudential.com.hk/PruServlet?module=fund&purpose=searchHistFund&fundCd=JAS_U

错了,怎么修改:

import pandas as pd
import requests
import re
url = 'http://www.prudential.com.hk/PruServlet?module=fund&purpose=searchHistFund&fundCd=JAS_U'
tables = pd.read_html(requests.get(url).text, attrs={"class":re.compile("fundPriceCell\d+")})

【问题讨论】:

  • 这是一个相当混乱的 html,我认为您将需要探索 xml 树以获取正确的值。 attr 类应该放在桌子上而不是单元格上(我认为)......
  • 对不起。这是否意味着我必须导入 BeautifulSoup4?有什么推荐吗?
  • 免责声明:我可能是错的,可能有一种巧妙的方法可以让 read_html 抓住它。如果没有,我设想的是这样的:stackoverflow.com/a/16993660/1240268,但它有点混乱/尴尬。

标签: python-2.7 pandas python-requests


【解决方案1】:

我喜欢用 lxml 来解析和查询 HTML。这是我想出的:

import requests
from lxml import etree

url = 'http://www.prudential.com.hk/PruServlet?module=fund&purpose=searchHistFund&fundCd=JAS_U'
doc = requests.get(url)
tree = etree.HTML(doc.content)

row_xpath = '//tr[contains(td[1]/@class, "fundPriceCell")]'

rows = tree.xpath(row_xpath)

for row in rows:
    (date_string, v1, v2) = (td.text for td in row.getchildren())
    print "%s - %s - %s" % (date_string, v1, v2)

【讨论】:

  • 代码中的“td”是什么?
  • @Egret - 在此示例中,生成器表达式用于迭代每一行(即表行,<tr>)的子元素,我们希望这些子元素是表数据(即 <td>)元素.
【解决方案2】:

我的解决方案和你的类似:

import pandas as pd
import requests
from lxml import etree

url = "http://www.prudential.com.hk/PruServlet?module=fund&purpose=searchHistFund&fundCd=JAS_U"
r = requests.get(url)
html = etree.HTML(r.content)
data = html.xpath('//table//table//table//table//td[@class="fundPriceCell1" or @class="fundPriceCell2"]//text()')

if len(data) % 3 == 0:
    df = pd.DataFrame([data[i:i+3] for i in range(0, len(data), 3)], columns = ['date', 'bid', 'ask'])
    df = df.set_index('date')
    df.index = pd.to_datetime(df.index, format = '%d/%m/%Y')
    df.sort_index(inplace = True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 2016-07-18
    • 2019-11-07
    相关资源
    最近更新 更多