我收到消息UnboundLocalError: local variable 'adict' referenced before assignment
但是我不理解该错误,因为我在分配键和值之前定义了adict
。
def output(query,s_date,e_date,page,max_page):
while page < max_page:
s_from = s_date.replace(".","")
e_to = e_date.replace(".","")
url = "https://search.naver.com/search.naver?where=news&query=" + query + "&sort=0&ds=" + s_date + "&de=" + e_date + "&nso=so%3Ar%2Cp%3Afrom" + s_from + "to" + e_to + "%2Ca%3A&start=" + str(page)
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
}
req = requests.get(url,headers=header)
cont = req.content
soup = BeautifulSoup(cont, 'html.parser')
jsonfile = open(s_from+"_news_scrape_"+e_to+".json", 'w')
news_dicts = []
for urls in soup.select("._sp_each_url"):
adict = dict()
try:
if urls["href"].startswith("https://news.naver.com"):
news_detail = get_news(urls["href"])
adict["title"] = news_detail[0]
adict["date"] = news_detail[1]
adict["company"] = news_detail[3]
adict["text"] = news_detail[2]
except Exception as e:
continue
page += 10
return adict
任何建议都将不胜感激,这需要我永远进行调试。
答案 0 :(得分:0)
我无法验证这一点,因为我无法复制您的问题,但是看起来您的for循环有时根本不执行(soup.select()
返回一个空列表)。因此,我怀疑您的退货单正在造成问题。
将adict = dict()
放在for循环之前,或确保在返回adict
之前,它实际上是首次初始化的。
>>> def test():
... if 1 == 2:
... adict = dict()
... return adict
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in test
UnboundLocalError: local variable 'adict' referenced before assignment