2015-10-05 80 views
-2

我遇到了一个小问题。这里是我的代码:分配前引用的局部变量'price_end'

front_deeplink = ("http://www.sozi.com") 

user_agent = {'User-agent': 'Chrome/43.0.2357.124'} 

Region = "turkey/istanbul" 


def trade_spider(max_pages): 
    page = 0 
    partner_ID = Yes 
    location_ID = No 

    try: 
     connection = mysql.connector.connect\ 
      (host = "localhost", user = "root", passwd ="", db = "local") 
    except: 
     print("Keine Verbindung zum Server") 
     sys.exit(0) 

    cursor = connection.cursor() 

    cursor.execute("DELETE from prices_crawled where LocationID=" + str(location_ID) + " and PartnerID=" + str(partner_ID)) 
    connection.commit() 

    while page <= max_pages: 
     page += 1 
     r = requests.get("http://www.zosi.com/things-to-do/" + str(Region) + "/?per_page=10&page=" + str(page)) 
     soup = BeautifulSoup(r.content) 


     g_data = soup.find_all("div", {"class": "column info"}) 

     for item in g_data: 
      Header = item.find_all("a") 
      for t in set(t.get("data-product-name") for t in Header): 
       Header_final = t 
      price = item.find_all("div", {"class": "price"}) 
      Price_final = (price[0].text.strip()[8:]) 
      if Price_final: 
       price_end = int(float(Price_final)*100*Change) 
      Deeplink = item.find_all("a") 
      for j in set(j.get("href") for j in Deeplink): 
       Deeplink_final = (str(front_deeplink) + j) 
      Language = "Englisch" 


      print("Header: " + Header_final + " | " + "Price: " + str(price_end) + " | " + "Deeplink: " + Deeplink_final + " | " + "PartnerID: " + str(partner_ID) + " | " + "LocationID: " + str(location_ID)+ " | " + "Language: " + Language) 

      cursor.execute('''INSERT INTO local2 (price_id, Header, Price, Deeplink, PartnerID, LocationID, Language) \ 
        VALUES(%s, %s, %s, %s, %s, %s, %s)''', ['None'] + [Header_final] + [price_end] + [Deeplink_final] + [partner_ID] + [location_ID] + [Language]) 

      connection.commit() 



    cursor.close() 
    connection.close() 
trade_spider(8) 

Outcome: 
File "C:/Users/hmattu/PycharmProjects/untitled1/grayline.com.py", line 84, in <module> 
trade_spider(8) 
    File "C:/Users/hmattu/PycharmProjects/untitled1/grayline.com.py", line 66, in trade_spider 
    print("Header: " + Header_final + " | " + "Price: " + str(price_end) + " | " + "Deeplink: " + Deeplink_final + " | " + "PartnerID: " + str(partner_ID) + " | " + "LocationID: " + str(location_ID)+ " | " + "Language: " + Language) 
UnboundLocalError: local variable 'price_end' referenced before assignment 

这个问题在我启动程序时开始。它打开控制台,但立即退出。它也不输出任何信息。 我不太确定发生了什么,如果有人可以帮助我,我会很感激。

+1

如果您打印到print(“Header:”...),但是如果Price_final从未为True,会发生什么?那么'price_end'将不会有任何价值。 – Kevin

回答

0

实际上,如果Price_finaltruthy,那么您只能为price_end赋值。解决办法是自己提出异常,或者分配一个值,该值是一个提供一些信息的字符串。

if Price_final: 
    price_end = int(float(Price_final)*100*Change) 
else: 
    raise ValueError('No Price can be evaluated') 
    #or price_end = 'No price can be evaluated' 
相关问题