您的程序中有一个错误,语法无效python 2.7.15

2024-09-29 17:17:22 发布

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

import urllib
import re

symbolslist = ["aaple", "spy", "goog", "nflx"]

i=0
while i<len(symbolslist):
   url = "http://finance.yahoo.com/q?s=" +symbolslist[i] +"&q1=1"
   htmlfile = urllib.urlopen(url)
   htmltext = htmlfile.read()
   regex = '<span id="yfs_184_'+symbolslist[i]'">(.+?)</span>'
   pattern = re.compile(regex)
   price = re.findall(pattern,htmltext)
   print "the price of", symbolslist[i]," is " ,price
   i+1

有人能告诉我上面的代码有什么问题吗? 谢谢


Tags: importreurlurllibpriceregexpatterngoog
3条回答

您丢失了+符号:

regex = '<span id="yfs_184_'+symbolslist[i]'">(.+?)</span>'
                                          ^
                                          |
here                   -

使用format-it使代码更具可读性https://pyformat.info/

你错过了regex = '<span id="yfs_184_'+symbolslist[i]'">(.+?)</span>'的第二个+

import urllib
import re

symbolslist = ["aaple", "spy", "goog", "nflx"]

for symbol in symbolslist:
   url = "http://finance.yahoo.com/q?s={symbol}&q1=1".format(symbol=symbol)
   htmlfile = urllib.urlopen(url)
   regex = '<span id="yfs_184_{symbol}">(.+?)</span>'.format(symbol=symbol)
   pattern = re.compile(regex)
   price = re.findall(pattern, htmlfile.read())
   print("the price of", symbol," is " ,price)

线路

regex = '<span id="yfs_184_'+symbolslist[i]'">(.+?)</span>'

symbolslist[i]之后需要+

regex = '<span id="yfs_184_'+symbolslist[i]+'">(.+?)</span>'

相关问题 更多 >

    热门问题