使用ruby

时间:2017-09-15 13:02:53

标签: ruby csv

我正在尝试在Google上自动搜索,因为我有超过1千行。我可以从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))

1 个答案:

答案 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