2015-01-20 121 views
2

我在Mac OS上使用Ruby 2.1.0p0。從CSV打開網址

我解析一個CSV文件並抓取所有的URL,然後使用Nokogiri和OpenURI來刮他們,這是我卡住的地方。

當我嘗試使用each遍歷數組的URL運行,我得到這個錯誤:

initialize': No such file or directory @ rb_sysopen - URL (Errno::ENOENT) 

當我手動創建一個數組,然後通過它運行我沒有得到任何錯誤。我試過to_sURI::encode,以及我能想到的所有東西,並在Stack Overflow上找到。

我可以使用puts在陣列上從CSV或從終端複製和粘貼URL,並在我的瀏覽器中打開沒有問題。我嘗試用Nokogiri打開它並沒有發生。

這裏是我的代碼:

require 'rubygems' 
require 'nokogiri' 
require 'open-uri' 
require 'uri' 
require 'csv' 

    events = Array.new 
    CSV.foreach('productfeed.csv') do |row| 
     events.push URI::encode(row[0]).to_s 

    end 


    events.each do |event| 

     page = Nokogiri::HTML(open("#{event}")) 

     #eventually, going to find info on the page, and scrape it, but not there yet. 

     #something to show I didn't get an error 
     puts "open = success" 


    end 

請幫幫忙!我完全沒有想法。

回答

3

它看起來像你正在處理標題行,這些值的字面意思是"URL"。這不是一個有效的URI,因此open-uri不會觸及它。

CSV模塊有一個headers選項可以自動使用標題。嘗試打開並參考row["URL"]

+0

BOOM!完美的作品。非常感謝。對此,我真的非常感激。請投票給這個傢伙!我沒有足夠的聲望。 :-( – 2015-01-20 18:53:37

+1

@JacksonRiso你可能沒有足夠的代表upvote(但),但你應該能夠[接受答案](http://stackoverflow.com/help/someone-answers)(它會給你一個小代表也是)。 – matt 2015-01-20 19:09:08

0

我試着做同樣的事情,發現它使用文本文件更好地工作。

這是我做的。

#!/usr/bin/python 

#import webbrowser module and time module 
import webbrowser 
import time 

#open text file as "dataFile" and verify there is data in said file 
dataFile = open('/home/user/Desktop/urls.txt','r') 
if dataFile > 1: 
     print("Data file opened successfully") 
else: 
     print("!!!!NO DATA IN FILE!!!!") 
     exit() 

#read file line by line, remove any spaces/newlines, and open link in chromium-browser 
for lines in dataFile: 
     url = str(lines.strip()) 
     print("Opening " + url) 
     webbrowser.get('chromium-browser').open_new_tab(url) 

#close file and exit 
print("Closing Data File") 
dataFile.close() 

#wait two seconds before printing "Data file closed". 
#this is purely for visual effect. 
time.sleep(2) 
print("Data file closed") 

#after opener has run, user is prompted to press enter key to exit. 
raw_input("\n\nURL Opener has run. Press the enter key to exit.") 

exit() 

希望這會有所幫助!