2015-01-20 70 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() 

希望这会有所帮助!