【问题标题】:How to use read_html to read a table with 2 class attrs?如何使用 read_html 读取具有 2 个类属性的表?
【发布时间】:2013-11-12 16:12:43
【问题描述】:

我正在尝试刮取以下地区的基金价格:

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

但是table中各行的class属性不同,有“class”:“fundPriceCell1”和“fundPriceCell2”:

<tr>
<td align="center" class="fundPriceCell1">08/11/2013</td><td align="center" class="fundPriceCell1">118.2500</td><td align="center" class="fundPriceCell1">118.2500</td>
</tr>
<tr>
<td align="center" class="fundPriceCell2">07/11/2013</td><td align="center" class="fundPriceCell2">118.9800</td><td align="center" class="fundPriceCell2">118.9800</td>
</tr>

如何刮桌子?这是错误的,但如何解决?

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

【问题讨论】:

  • 如果你的后端 html 解析器是 beutifulsoup,我猜你可以传递一个编译的正则表达式作为你的 attrs 字典中 'class' 元素的值
  • 这是一个属性字典,我可以通过它来识别 HTML 中的表格。如何传递已编译的正则表达式?

标签: python-2.7 pandas python-requests


【解决方案1】:

我认为您可以传递已编译的正则表达式,并且此语法将匹配两个 class 属性:

import re
tables = pd.read_html(requests.get(url).text, attrs={"class":re.compile("fundPriceCell\d+")})

【讨论】:

  • 现在我得到了:AssertionError: No tables found
  • 您在帖子中输入的常量也会出现该错误,但这与您要求解决的问题无关。
猜你喜欢
  • 2016-07-18
  • 2013-11-27
  • 1970-01-01
  • 2011-03-09
  • 2013-05-03
  • 1970-01-01
  • 2020-05-08
  • 2018-01-11
  • 1970-01-01
相关资源
最近更新 更多