2016-12-25 75 views
0

我一直在試圖讓我的腳本循環以這樣的方式,它將加載1個文件中的輸出,然後當它完成加載一切移動值輸出文件2,擦除輸出文件1中的值並開始重新加載它們,然後當這些值向下移動到輸出2(覆蓋舊的)時重複。「Unboundlocalerror:本地變量」Val「分配之前引用」錯誤

到目前爲止,我一直非常成功,不知道還有什麼要添加到我的腳本,我希望這裏有人知道爲什麼我不斷收到「」Unboundlocalerror:本地變量「Val」分配之前引用「錯誤隨機中途加載過程中,當我有一個非常小的輸入文件,腳本執行我想要的。

有誰知道我可以如何更改我的腳本來修復該錯誤,我試圖理解它爲什麼會發生,但不能。

我試圖徹底研究它,但沒有發現我的建議已經奏效(或者我錯誤地實現了它們,我已經附上了我的腳本。謝謝!

import urllib2,re,urllib,urlparse,csv,sys,time,threading,codecs,shutil 
    from bs4 import BeautifulSoup 


    def extract(url): 
     try: 
      sys.stdout.write('0') 
      # global file 
      page = urllib2.urlopen(url).read() 

      soup = BeautifulSoup(page, 'html.parser') 

      product = soup.find("div", {"class": "js-product-price"}) 
      price = product.findNext('div',{'class': 'js-price-display'}).getText().strip() 
      oos = product.findNext('p', attrs={'class': "price-oos"}) 

      if oos is None: 
       oos = 'In Stock' 
      else: 
       oos = oos.getText() 

      val = url + "," + price + "," + oos + "," + time.ctime() + '\n' 
      # ifile.write(val) 
      sys.stdout.write('1') 
     except Exception as e: 
      print e 

     return val 

    while True: 
     ifile = open('output.csv', "w", 0) 
     inputs = csv.reader(open('input.csv')) 
     # inputs = csv.reader(codecs.open('input.csv', 'rU', 'utf-16')) 

     ifile.write('URL' + "," + 'Price' + "," + 'Stock' + "," + "Time" + '\n') 

     for i in inputs: 
      ifile.write(extract(i[0])) 
     ifile.close() 

更新:

感謝您的幫助傢伙!這是我的新的腳本:

import urllib2,re,urllib,urlparse,csv,sys,time,threading,codecs,shutil 
from bs4 import BeautifulSoup 


def extract(url): 
    try: 
     sys.stdout.write('0') 
     # global file 
     page = urllib2.urlopen(url).read() 

     soup = BeautifulSoup(page, 'html.parser') 

     product = soup.find("div", {"class": "js-product-price"}) 
     price = product.findNext('div',{'class': 'js-price-display'}).getText().strip() 
     oos = product.findNext('p', attrs={'class': "price-oos"}) 

     if oos is None: 
      oos = 'In Stock' 
     else: 
      oos = oos.getText() 

     val = url + "," + price + "," + oos + "," + time.ctime() + '\n' 
     # ifile.write(val) 
     sys.stdout.write('1') 
    except Exception as e: 
     print e 

    else: 
     return val 

while True: 
    ifile = open('output.csv', "w", 0) 
    inputs = csv.reader(open('input.csv')) 
    # inputs = csv.reader(codecs.open('input.csv', 'rU', 'utf-16')) 

    ifile.write('URL' + "," + 'Price' + "," + 'Stock' + "," + "Time" + '\n') 

    for i in inputs: 
     val_to_write = extract(i[0]) 
     if val_to_write: 
      ifile.write(val_to_write) 
     ifile.close() 

    shutil.copy('output.csv', 'output2.csv') 

print("finished") 

有了上面的腳本我現在得到的錯誤:「ValueError異常:在關閉的文件I/O操作」。謝謝

回答

0

使用try-except-else因爲你只想return val如果沒有發生異常(如果發生異常,則val將不會被分配給當你試圖return它)。另一個建議是不要使用「全部抓取」塊。

def extract(url): 
    try: 
     sys.stdout.write('0') 
     # global file 
     page = urllib2.urlopen(url).read() 

     soup = BeautifulSoup(page, 'html.parser') 

     product = soup.find("div", {"class": "js-product-price"}) 
     price = product.findNext('div',{'class': 'js-price-display'}).getText().strip() 
     oos = product.findNext('p', attrs={'class': "price-oos"}) 

     if oos is None: 
      oos = 'In Stock' 
     else: 
      oos = oos.getText() 

     val = url + "," + price + "," + oos + "," + time.ctime() + '\n' 
     # ifile.write(val) 
     sys.stdout.write('1') 
    except Exception as e: 
     print e 

    else: 
     return val 

但要注意:如果出現了異常,然後extract將返回None和調用代碼將不得不考慮的,例如:

for i in inputs: 
    val_to_write = extract(i[0]) 
    if val_to_write: 
     ifile.write(val_to_write) 
    ifile.close() 
+0

非常感謝你的回覆! !我正在嘗試它。我一直在努力工作多年。非常感謝 – Pythonhelpneeded

+0

嘿,所以我給它一個旋風,現在我得到「ValueError:關閉文件上的I/O操作」後加載1或2的東西 - 任何想法? – Pythonhelpneeded

+0

不要在'while True'循環中打開'並'關閉'文件。 – DeepSpace

相關問題