我如何用漂亮的汤解析雅虎财务信息

时间:2019-01-22 17:19:57

标签: beautifulsoup yahoo-finance

到目前为止,我已经使用了soup.findAll('span')

<span data-reactid="12">Previous Close</span>,
     <span class="Trsdu(0.3s) " data-reactid="14">5.52</span>,
     <span data-reactid="17"></span>,
     <span class="Trsdu(0.3s) " data-reactid="19">5.49</span>,
     <span data-reactid="38">Volume</span>,
     <span class="Trsdu(0.3s) " data-reactid="40">1,164,604</span>,
     ...

我想要让我看到的脚印

Open 5.49
Volume 1,164,604

... 我尝试了soup.findAll('span')。text,但它给出了错误消息:

ResultSet object has no attribute 'text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?

这是来源:

https://finance.yahoo.com/quote/gxl.ax?p=gxl.ax

2 个答案:

答案 0 :(得分:2)

幸运的是,错误提示了我们

  

您可能正在将一系列项目视为单个项目。当您打算致电find()时,您是否致电过find_all()?

尝试以下方法之一:

soup.findAll('span')[0].text
soup.findAll('span')[i].text
soup.find('span').text

在浏览许多选择器系统(包括CSS选择器)时,这是一个通用问题。要对元素进行操作,它必须是单个元素,而不是集合。 findAll()返回一个集合(数组),因此您可以索引到该数组(例如[i]),也可以使用find()找到第一个匹配项。

答案 1 :(得分:2)

soup.findAll('span')将返回ResultSet中的对象/元素。您必须遍历所有内容以打印文本。因此,尝试:

spans = soup.findAll('span')
for ele in spans:
    data = ele.text
    print(data)

要获取输出并放入数据框:

your_output = ['Previous Close', '5.52', 'Open', '5.49', 'Bid', 'Ask', "Day's Range", '52 Week Range', 'Volume', '1,164,604', 'Avg. Volume', '660,530']

headers = your_output[::2]
data = your_output[1::2]

df = pd.DataFrame([data], columns = headers)

其他

您当然可以使用BeautifulSoup通过遍历元素来解析并放入数据框。我想为BeautifulSoup提供一个替代。

Pandas如果可以使用.read_html来识别html中的表格,则可以为您完成大部分工作。您可以使用它来实现要查找的表的数据框类型。

import pandas as pd

tables = pd.read_html(url)
df = pd.concat( [ table for table in tables ] )

输出:

print (df)
                          0             1
0            Previous Close          5.50
1                      Open          5.50
2                       Bid      5.47 x 0
3                       Ask      5.51 x 0
4               Day's Range   5.47 - 5.51
5             52 Week Range   3.58 - 6.49
6                    Volume        634191
7               Avg. Volume        675718
0                Market Cap      660.137M
1         Beta (3Y Monthly)          0.10
2            PE Ratio (TTM)         31.49
3                 EPS (TTM)          0.17
4             Earnings Date           NaN
5  Forward Dividend & Yield  0.15 (2.82%)
6          Ex-Dividend Date    2019-02-12
7             1y Target Est          5.17