2017-09-15 49 views
0

我想在Google上自動搜索,因爲我有超過1000行。我可以從CSV中讀取和自動執行搜索,但無法將該數組添加到文件中。也許我錯過了什麼?使用ruby在第二列添加數組到csv文件

對於測試,CSV文件由1列組成,沒有標題和3行。

這裏是我的代碼:

require 'watir' 
require 'nokogiri' 
require 'csv' 

browser = Watir::Browser.new(:chrome) 
browser.goto("http://www.google.com") 
CSV.open('C:\Users\Market\Documents\Emailhunter_scraper\test-email.csv').map do |terms| 
browser.text_field(title: "Rechercher").set terms 
browser.send_keys :return 

sleep(rand(10)) 
doc = Nokogiri::HTML.parse(browser.html) 
doc.css("div.f kv _SWb").each do |item| 
    name = item.css('a').text 
    link = item.css('a')[:href] 
    csv << [name, link] 
end 
sleep(rand(10)) 
end 
sleep(rand(10)) 
+0

我猜這個問題是,你還沒有打開CSV文件的寫作。試試這個:'CSV.open('path/to/file/csv','wb')' – hoffm

+0

感謝您的解決方案,它的確寫了我的csv。唯一的問題是:它什麼都不寫並且會把所有的東西都寫下來...... 我在做什麼錯了? 我的csv文件有2列(實體,url)和3行(a,b,c) 我知道如何告訴Ruby查找每行,但不知道如何告訴Ruby在列url中寫入鏈接解析對應於實體讀取。我不知道我是否足夠清楚,所以不要猶豫,打我回來;) –

+0

我的問題的任何更新? –

回答

1

the documentation for CSV.open所示,文件mode默認爲"rb"

這意味着該文件正在打開爲只讀。相反,您需要使用:

CSV.open('path/to/file/csv', 'wb') 

不同模式的完整文檔可以看到here。他們是:

"r" Read-only, starts at beginning of file (default mode). 

"r+" Read-write, starts at beginning of file. 

"w" Write-only, truncates existing file 
    to zero length or creates a new file for writing. 

"w+" Read-write, truncates existing file to zero length 
    or creates a new file for reading and writing. 

"a" Write-only, each write call appends data at end of file. 
    Creates a new file for writing if file does not exist. 

"a+" Read-write, each write call appends data at end of file. 
    Creates a new file for reading and writing if file does 
    not exist. 

"b" Binary file mode 
    Suppresses EOL <-> CRLF conversion on Windows. And 
    sets external encoding to ASCII-8BIT unless explicitly 
    specified. 

"t" Text file mode 
+0

OMG我好蠢!你在很久以前回答了我,我只是明白......非常感謝! –