我正在尝试运行以下脚本,但继续收到一个错误,即我的变量“doc_id”在赋值之前被引用,我找不到解决方案。请参阅下面的代码。我不得不删掉一些代码,但如果有用的话,我很乐意发表评论
感谢您的帮助
def writeBills():
bill_id_list= []
for item in js.values():
try:
bill_id_list.append(item.get('bill_id'))
except KeyError:
pass
bills = getBills(bill_id_list)
num = 1
for bill in bills:
#iterate to the bill key
#get the doc_id to append to the API call
try:
bill_num = bill.get("bill").get("bill_number")
except AttributeError:
bill_num = "bill" + str(num)
try:
doc_id = bill.get("bill").get("texts")[0].get("doc_id")
except AttributeError:
pass
#append the doc_id to the API call and convert results to unicode string
searchId = urlopen('https://api.legiscan.com/?key=d43c289757d4acd3bdb73391fb60e97a&op=getBillText&id='+str(doc_id)).read().decode()
#create json object with API data
resultsId = json.loads(searchId)
#iterate to the document object
resultsId = resultsId.get('text').get('doc')
#decode the MIME 64 encoded text
decodedResults = base64.b64decode(resultsId)
#once decoded, the text is in an HTML string, use bs4 to parse it
bsObj2 = BeautifulSoup(decodedResults)
for p in bsObj2.find_all('p'):
if p.string:
p.string.replace_with(p.string.strip())
bsObj2.style.decompose()
#strip white space, encode in ascii and remove non-printing characters
htmlText = str(bsObj2.getText())
f = open("~/repos/LegiScanApiScrips/data/bills/" + str(bill_num) + "_" + str(doc_id) + ".txt", "wb")
print("Writing: "+ str(bill_num))
f.write(htmlText.encode("ascii", errors="ignore"))
f.close()
num += 1
writeBills()
这里有一个
AttributeError
正在被提升,你正在吞咽,所以doc_id
没有被初始化变量
doc_id
仅在没有AttributeError
但您正在以任何方式使用doc_id
时才赋值请尝试以下方法:
顺便说一句,不要在应用程序流中涉及异常处理
相关问题 更多 >
编程相关推荐