python - 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
最好的结果是它获得了股票图表的所有链接,可以告诉我哪个股票代码遇到错误并继续运行剩余的代码
谢谢你
解决方案
当符号不存在时不会抛出异常。这意味着它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"
推荐阅读
- java - 尝试使用 getInorderIterator 但它没有打印我的树 InOrder
- java - 逐行读取非阻塞 java.nio SocketChannel
- javascript - 如何检查文件名是否包含带有 Mocha/Chai 的字符串?
- java - 如何使用方法修复“实际参数列表和形式参数列表的长度不同”?
- laravel - 使用“GrahamCampbell/Laravel-GitHub”时如何修复“Http\Adapter\Guzzle6\Client::buildClient() 的参数太少”
- interrupt-handling - 从哪里开始键盘中断处理程序
- android - 在 Android 4.2 上与 WhatsApp 共享音频文件失败
- r - 如何解决network_plot中的错误“找不到对象'X1'”?
- php - 来自 PHP 响应的通过 jQuery 的 AJAX 请求 null
- javascript - Jexcel 删除所有单元格并在 if 语句上留下数字 1