Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 美丽的汤出索引_Python 3.x_Beautifulsoup - Fatal编程技术网

Python 3.x 美丽的汤出索引

Python 3.x 美丽的汤出索引,python-3.x,beautifulsoup,Python 3.x,Beautifulsoup,我正在尝试创建一个简单的程序,当我输入一个谷歌财务地址时,打印股票价格 我目前使用的代码如下 import requests import bs4 def pricechecker(url): r = requests.get(url) soup = bs4.BeautifulSoup(r.text, 'html5lib') print (soup.select('span.unchanged')[0].text) 当我运行我一直用作参数的代码时。在运行代码时,它声明列

我正在尝试创建一个简单的程序,当我输入一个谷歌财务地址时,打印股票价格

我目前使用的代码如下

import requests
import bs4
def pricechecker(url):
    r = requests.get(url)
    soup = bs4.BeautifulSoup(r.text, 'html5lib')
    print (soup.select('span.unchanged')[0].text)
当我运行我一直用作参数的代码时。在运行代码时,它声明列表索引超出范围。我使用firebug获得了汤的CSS。选择代码的一部分

任何帮助都将不胜感激,因为我是编程新手,希望纠正我的错误

最好的


Hunter

快速检查显示,您从该请求获得的原始html中的任何位置都不会“未更改”:请尝试运行

curl http://www.google.com/finance?q=NASDAQ%3AAAPL&ei=4UJrVomFNZGje7y-pJAP | grep "unchanged"
不会有结果

或者,如果您不喜欢命令行,可以在python中尝试:

r = requests.get(url)
print("unchanged" in r.text)  # will be False
没有匹配项。这是因为只有当页面的javascript将数据加载到同样在javascript中生成的
标记中时,“未更改”值才会显示

您可以使用以下方法获取此数据。当然首先安装:
pip安装googlefinance
。然后

from googlefinance import getQuotes
aapl = getQuotes('AAPL')
print(aapl)  # provides a bunch of info in a list including...
last_price = aapl[0]['LastTradePrice']

last\u price
是一个字符串,因此要转换为浮点,
float(aapl[0]['LastTradePrice'])
提示:执行
print(soup.select('span.unchanged'))
以查看结果,我在尝试索引到它之前尝试了一次,它只返回空列表。我不知道这是为什么。那么,当你为一张空名单编制索引时,你期待什么呢?我想让它打印股票的价格。你必须从网站上刮下来吗?有更好的方法获取股票价格。我的猜测是,有一个脚本运行来填充您试图刮取的字段。因此,由于您是在浏览器之外请求html,javascript无法填充它。