漂亮的汤缺少数据

时间:2018-10-21 13:29:47

标签: python beautifulsoup

我正在使用漂亮的汤来尝试从几个不同的站点上刮取一些财务信息,但是我注意到,大多数html信息在我刮擦的内容中都丢失了。解析抓取的信息时没有运气,我尝试过html.parserlxmlhtml5lib

下面是我在两个尝试过的不同站点上使用过的代码示例。在这两个示例中,我都尝试检索市值信息,但似乎从未在解析后的输出中获取它。

#!/usr/bin/env python

def get_marketcap(security):
    from bs4 import BeautifulSoup as bs
    from urllib.request import urlopen

    loc = 'https://stockrow.com/AAPL'
    loc = 'https://www.wolframalpha.com/input/?i=GOOGL+historical+market+capitalization+1.7.2018-1.10.2018'
    page = urlopen(loc)
    #soup = bs(page, 'html.parser')
    #soup = bs(page, 'lxml')
    soup = bs(page, 'html5lib')

    return soup, name_box


soup,name_box = get_marketcap('AAPL')

2 个答案:

答案 0 :(得分:3)

所需数据来自XHR,您可以直接通过API请求获得它:

import requests

response_content =  requests.get('https://stockrow.com/api/companies/AAPL.json?ticker=AAPL').json()
print(response_content['prices'][0]['close'])
# 219.31

更新

如果您需要表格中的值(例如市值值),则可以使用

response_content =  requests.get('https://stockrow.com/api/companies/AAPL/key_stats.json?ticker=AAPL').json()
print([item['value'] for item in response_content if item['indicator'] == "MARKETCAP:MRM"][0])
#  1077938914780.0000 # 1077938914780.0000 == 1,077,938.91m

以相同的方式,您可以提取其他值,例如企业价值(键-{"EV:MRM"),收入(键-"REVENUE:MRT"),等等...只需将上述代码行中的"MARKETCAP:MRM"键替换为适当的键

答案 1 :(得分:1)

如评论中所建议,您将能够使用精彩的requests-html库(由请求的创建者获取)来捕获JavaScript呈现的元素。您可以调整睡眠/等待时间,但是下面的代码可用于您的链接,并返回完整的html内容。

def get_marketcap(url_path):
    from requests_html import HTMLSession
    session = HTMLSession()

    r = session.get(url_path)
    r.html.render(wait = 8, sleep = 8)

    return r.html

#url_path = 'https://www.wolframalpha.com/input/?i=GOOGL+historical+market+capitalization+1.7.2018-1.10.2018'
url_path = 'https://stockrow.com/AAPL'
content = get_marketcap(url_path)
print(content.html)

还请注意,它requests-html不支持iPython,输出可以保存在文本文件中,也可以打印以查看。