【问题标题】:Web Scraping Google Finance网页抓取 Google 财经
【发布时间】:2013-11-30 03:12:32
【问题描述】:

我正在尝试自学如何通过网络抓取股票数据。我是一个新手,所以请原谅我可能会问的任何愚蠢的问题。

这是我的价格抓取代码,我也在尝试抓取 PE 比率。

import urllib.request
from bs4 import BeautifulSoup

start = 'http://www.google.com/finance?cid=694653'

page = urllib.request.urlopen(start)
soup = BeautifulSoup(page)


P = soup.find('span',{'id':'ref_694653_l'})

print(P.get_text())


pe = soup.find_all('td',{'class':'val'})

print(pe[5].get_text())

pe = soup.find('td',{'data-snapfield':'pe_ratio'})

print(pe.td.next_sibling.get_text())

我可以得到价格数据,我设法得到了市盈率,但不是直接的。我尝试使用 next_sibling 和 next_element 但它给了我一个错误,说没有属性。

我无法弄清楚如何从表中抓取数据,因为它通常是按行设置的,并且数据周围的类通常非常常见,例如 or 。

所以只是想寻求一些帮助来抓取市盈率。

谢谢大家

是的

【问题讨论】:

    标签: python beautifulsoup screen-scraping


    【解决方案1】:

    这会有所帮助:

    >>> pe = soup.find('td',{'data-snapfield':'pe_ratio'})
    >>> pe
    <td class="key" data-snapfield="pe_ratio">P/E
    </td>
    >>> print(pe.td.next_sibling.get_text())
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'next_sibling'
    >>> 
    >>> 
    >>> 
    >>> pe
    <td class="key" data-snapfield="pe_ratio">P/E
    </td>
    >>> pe.td
    >>> pe.next_sibling
    u'\n'
    >>> pe.next_sibling.next_sibling
    <td class="val">29.69
    </td>
    >>> pe.next_sibling.next_sibling.get_text()
    u'29.69\n'
    

    【讨论】:

    • 谢谢卡兰!如果我理解正确,那是我的错误,因为在 pe 变量中,标签已经包含,所以放置 pe.td.next_sibling.next_sibling 是错误的,因为 td 是额外的?
    • 是的。如果答案有帮助,请点赞。如果它回答了您的问题,请将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 2018-07-11
    • 2019-06-15
    • 2019-11-05
    • 2017-12-28
    • 2020-09-10
    • 2019-08-17
    • 2017-01-14
    • 1970-01-01
    相关资源
    最近更新 更多