【问题标题】:Open URLs from CSV从 CSV 打开 URL
【发布时间】:2015-03-19 03:02:12
【问题描述】:

我在 Mac OS 上使用 Ruby 2.1.0p0。

我正在解析一个 CSV 文件并抓取所有 URL,然后使用 Nokogiri 和 OpenURI 来抓取它们,这是我遇到的问题。

当我尝试使用 each 循环遍历 URLs 数组时,我收到此错误:

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

请帮忙!我完全没有想法。

【问题讨论】:

    标签: ruby csv nokogiri


    【解决方案1】:

    看起来您正在处理标题行,其中一个值实际上是"URL"。这不是一个有效的 URI,所以 open-uri 不会碰它。

    CSV 模块有一个headers 选项,可以自动使用标题。尝试打开它并参考row["URL"]

    【讨论】:

    • 轰隆隆!完美运行。太感谢了。对此,我真的非常感激。请给这个人投票!我没有足够的声望。 :-(
    • @JacksonRiso 你可能没有足够的代表来投票(还),但你应该能够accept the answer(这也会给你一点代表)。
    【解决方案2】:

    我尝试做同样的事情,发现使用文本文件效果更好。

    这就是我所做的。

    #!/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()
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 2015-12-12
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 2019-07-23
      • 2020-11-06
      相关资源
      最近更新 更多