首页 > 解决方案 > Python Web抓取股票图表,找不到股票代码时代码卡住

问题描述

我有一个股票代码列表要在这个网站上运行,然后希望获得股票图表的链接

但是,当符号出现错误时,网站会重定向到另一个页面,python 会停止运行剩余的符号

我的符号列表是:WOW、AAR、TPM

错误发生在 AAR

谁能给这个Py noob一些指导?


from urllib import urlopen
from bs4 import BeautifulSoup
import re

newsymbolslist = ['WOW','AAR','TPM']

i=0

try:
    while i < len(newsymbolslist):
        try:
            html = urlopen( 'http://bigcharts.marketwatch.com/quickchart/quickchart.asp?symb=AU%3A'+newsymbolslist[i])
            bs = BeautifulSoup(html, 'html.parser')
            images = bs.find_all('img', {'src': re.compile('market')})
            for image in images:
                print (image['src'] + '\n')
                i += 1
        except:
            print "error"
            i += 1
except:
    pass

最好的结果是它获得了股票图表的所有链接,可以告诉我哪个股票代码遇到错误并继续运行剩余的代码

谢谢你

标签: pythonloopsredirectweb-scraping

解决方案


当符号不存在时不会抛出异常。这意味着它i不会增加,因为它在 for 循环中迭代找到的图像(在 AAR 情况下只是一个空列表)。结果是i永远不会满足打破 while 循环的条件,它会永远继续下去。将i+=1移入 finally 块可确保它始终递增。

from urllib import urlopen
from bs4 import BeautifulSoup
import re
newsymbolslist = ['WOW','AAR','TPM']
i=0
try:
    while i < len(newsymbolslist):
        try:
            html = urlopen( 'http://bigcharts.marketwatch.com/quickchart/quickchart.asp?symb=AU%3A'+newsymbolslist[i])
            bs = BeautifulSoup(html, 'html.parser')
            images = bs.find_all('img', {'src': re.compile('market')})
            for image in images:
                print (image['src'] + '\n')      
        except Exception as e:
            print "error"
        finally:
            i += 1
except:
    pass

作为一种改进,您可以通过迭代您拥有的符号列表来完全删除 while 循环。然后你不需要担心递增i

for symbol in newsymbolslist:
    try:
        html = urlopen( 'http://bigcharts.marketwatch.com/quickchart/quickchart.asp?symb=AU%3A'+symbol)
        bs = BeautifulSoup(html, 'html.parser')
        images = bs.find_all('img', {'src': re.compile('market')})
        for image in images:
            print (image['src'] + '\n')      
    except Exception as e:
        print "error"

推荐阅读