Python错误——赋值前引用局部变量



我收到消息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

任何建议都将不胜感激,这将花费我很长时间进行调试。

我无法验证这一点,因为我无法复制您的问题,但有时您的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

相关内容

最新更新