Python 跳过数据不可用的网页的条件
我正在尝试从“”网站获取数据。我写了下面的脚本,但问题是给定站点中的一些站点没有任何数据。所以它给出的错误是'AttributeError:'NoneType'对象没有属性'text'。我想写一些条件,以便在没有数据的地方跳过该站,转到下一站 尝试: 对于车站内的stn:Python 跳过数据不可用的网页的条件,python,web-scraping,attributeerror,Python,Web Scraping,Attributeerror,我正在尝试从“”网站获取数据。我写了下面的脚本,但问题是给定站点中的一些站点没有任何数据。所以它给出的错误是'AttributeError:'NoneType'对象没有属性'text'。我想写一些条件,以便在没有数据的地方跳过该站,转到下一站 尝试: 对于车站内的stn: year = '2017' month = '08' day = '14' hour = '00' end = '12' url = requests.get('http://weat
year = '2017'
month = '08'
day = '14'
hour = '00'
end = '12'
url = requests.get('http://weather.uwyo.edu/cgi-bin/sounding?region=naconf&TYPE=TEXT%3ALIST&YEAR='+year+'&MONTH='+month+'&FROM='+day+hour+'&TO='+day+end+'&STNM='+str(stn))
webbrowser.open(“+year+”&月=“+MONTH+”&从=“+day+hour+”&到=“+day+end+”&STNM=”+str(stn))
除属性错误外:
打印(“站点无可用数据”,属性错误)
webbrowser.open(“+year+”&月=“+MONTH+”&从=“+day+hour+”&到=“+day+end+”&STNM=”+str(stn))
我希望它应该通过跳过数据不可用的站点来打印数据可用站点的数据。但输出是:
没有站点可用的数据
回溯(最近一次呼叫最后一次):
文件“sound.py”,第30行,在
data=data\u box.text.strip()
AttributeError:“非类型”对象没有属性“文本”您的异常处理范围错误;异常被冒泡出来并捕获到for循环的外部,因此
for
循环已经在该点退出
您需要设置try except
,您认为可以在for
循环中引发异常,即选择最小范围:
for stn in station:
...
try:
data = data_box.text.strip()
except AttributeError :
print("No data available for station", AttributeError)
continue # move onto next station
import sys
import webbrowser
import urllib3
import requests
import lxml.html as lh
import pandas as pd
from time import sleep
from bs4 import BeautifulSoup
import csv
station =[42647,42101] # [42101] #,42647,42971,43371]
try:
for stn in station:
year = '2017'
month = '08'
day = '14'
hour = '00'
end = '12'
url = requests.get('http://weather.uwyo.edu/cgi-bin/sounding?region=naconf&TYPE=TEXT%3ALIST&YEAR='+year+'&MONTH='+month+'&FROM='+day+hour+'&TO='+day+end+'&STNM='+str(stn))
soup = BeautifulSoup(url.text,'html.parser')
data_box = soup.find('pre')
data = data_box.text.strip()
except AttributeError :
print("No data available for station", AttributeError)
print (data)
for stn in station:
...
try:
data = data_box.text.strip()
except AttributeError :
print("No data available for station", AttributeError)
continue # move onto next station