【问题标题】:Extracting a row from a table from a url从 url 从表中提取一行
【发布时间】:2017-02-01 16:12:27
【问题描述】:

我想从以下链接下载所有年份的 EPS 值(在年度趋势下)。 http://www.bseindia.com/stock-share-price/stockreach_financials.aspx?scripcode=500180&expandable=0

我尝试使用以下答案中提到的 Beautiful Soup。 Extracting table contents from html with python and BeautifulSoup 但是在下面的代码之后无法继续。我觉得我非常接近我的答案。任何帮助将不胜感激。

from bs4 import BeautifulSoup
import urllib2
html = urllib2.urlopen("http://www.bseindia.com/stock-share-price/stockreach_financials.aspx?scripcode=500180&expandable=0").read()
soup=BeautifulSoup(html)
table = soup.find('table',{'id' :'acr'})
#the below code wasn't working as I expected it to be
tr = table.find('tr', text='EPS')

我愿意使用任何其他语言来完成这项工作

【问题讨论】:

  • 你得到了什么出乎意料的结果?
  • 对象 tr 为空

标签: python html web-scraping beautifulsoup


【解决方案1】:

文本在 td 而不是 tr 所以使用文本获取 td 然后调用 .parent em> 得到 tr:

In [12]: table = soup.find('table',{'id' :'acr'})

In [13]: tr = table.find('td', text='EPS').parent

In [14]: print(tr)
<tr><td class="TTRow_left" style="padding-left: 30px;">EPS</td><td class="TTRow_right">48.80</td>
<td class="TTRow_right">42.10</td>
<td class="TTRow_right">35.50</td>
<td class="TTRow_right">28.50</td>
<td class="TTRow_right">22.10</td>
</tr>
In [15]: [td.text for td in tr.select("td + td")]
Out[15]: [u'48.80', u'42.10', u'35.50', u'28.50', u'22.10']

您将看到的内容与页面上的内容完全匹配。

另一种方法是调用 find_next_siblings

In [17]: tds = table.find('td', text='EPS').find_next_siblings("td")

In [18]: tds
Out[19]: 
[<td class="TTRow_right">48.80</td>,
 <td class="TTRow_right">42.10</td>,
 <td class="TTRow_right">35.50</td>,
 <td class="TTRow_right">28.50</td>,
 <td class="TTRow_right">22.10</td>]
In [20]: [td.text for td in tds]
Out[20]: [u'48.80', u'42.10', u'35.50', u'28.50', u'22.10']

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2019-11-03
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2013-10-20
    • 2012-08-17
    • 2016-09-15
    相关资源
    最近更新 更多