不同列表的索引超出范围

2024-06-29 00:55:21 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,当我运行我的程序与任何其他一个“天空”*它会工作,但当我运行它与天空它不工作

import urllib
import re

newsymbolslist = ["NFLX", "GOOG", "VNR", "AAPL", "SKY"]

i=0
while i<len(newsymbolslist):
    url = ("http://www.nasdaq.com/symbol/" +newsymbolslist[i]+ "/real-time")
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()
    regex = '<span id="quotes_content_left_OverallStockRating1_lblPercentage" class="comm_bullrating">(.+?)</span>'
    pattern = re.compile(regex)
    price = re.findall(pattern,htmltext)

    print (newsymbolslist[i] + " is: " + price[0])

    i+=1

*天空是新闻符号列表中的最后一个符号


Tags: import程序reurl符号urllibpriceregex
3条回答

由regex for SKY提取的信息已损坏,如下所示:

import urllib
import re

newsymbolslist = ["NFLX", "GOOG", "VNR", "AAPL", "SKY"]

i=0
while i<len(newsymbolslist):
    url = ("http://www.nasdaq.com/symbol/" +newsymbolslist[i]+ "/real-time")
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()
    regex = '<span id="quotes_content_left_OverallStockRating1_lblPercentage" class="comm_bullrating">(.+?)</span>'
    pattern = re.compile(regex)
    price = re.findall(pattern,htmltext)

    print (newsymbolslist[i] + " is: " + str (price))

    i+=1

enter image description here

在列表上循环的一种更为python的方式是:

import urllib
import re

newsymbolslist = ["NFLX", "GOOG", "VNR", "AAPL", "SKY"]

for symbol in newsymbolslist:
    url = ("http://www.nasdaq.com/symbol/" + symbol + "/real-time")
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()
    regex = '<span id="quotes_content_left_OverallStockRating1_lblPercentage" class="comm_bullrating">(.+?)</span>'
    pattern = re.compile(regex)
    price = re.findall(pattern,htmltext)

    print (symbol + " is: " + price[0])

sky的问题是类是comm_50rating,而不是comm_bullrating

因为nasdaq.com不会返回包含SKY的<span id="quotes_content_left_OverallStockRating1_lblPercentage" class="comm_bullrating">标记的页面

相关问题 更多 >