Skip to content

Instantly share code, notes, and snippets.

@srpouyet
Created August 3, 2010 13:01
Show Gist options
  • Save srpouyet/506333 to your computer and use it in GitHub Desktop.
Save srpouyet/506333 to your computer and use it in GitHub Desktop.
Zoeken op ISBN op bol.com en Selexyz.nl
# Dit script leest de ISBN nummers uit isbn.csv uit en zoekt het ISBN-nummer vervolgens op op bol.com en selexyz.nl.
# In theorie is er maximaal één resultaat. De productpaginalinks worden weggeschreven in aangevuld_isbn.csv
require 'mechanize'
require 'csv'
# Browser agent maken. Agent alias is optioneel
agent = Mechanize.new { |agent|
agent.user_agent_alias = 'Mac Mozilla'
}
# Laad de isbn nummers uit csv bestand met kolomnamen 'isbn','bol','selexyz'. CSV-scheidingsteken in NL is ; ipv ,
table = CSV.read("isbn.csv", :col_sep => ";", :headers => true)
# Voor ieder ISBN nummer zoekacties uitvoeren
table.each do |row|
# Zoeken op Bol.com
page = agent.get('http://www.bol.com/nl/index.html')
form = page.forms.first
form['/com/bol/search/form/QuickSearchFormHandler.Ntt'] = row['isbn']
page = agent.submit(form)
bol = ''
# Zoeken adh xpath-expressie (Nokogiri).
#Soms wordt er geen resultaat gevonden (nil), om errors te voorkomen omslachtig checken op nil
unless agent.page.search(".//a[@class='link_title']").first.nil?
bol = agent.page.search(".//a[@class='link_title']").first.attribute("href")
end
# Schrijf result weg naar kolom bol in csv
row['bol'] = 'http://www.bol.com' + bol
# puts bol
# Zoeken op Selexyz.nl
page = agent.get('http://www.selexyz.nl')
form = page.forms.first
form['q'] = row['isbn']
page = agent.submit(form)
selexyz = ''
unless agent.page.search("/html/body/div/div[2]/div[2]/div/div[2]/div/div[2]/div/h3/a").first.nil?
selexyz = agent.page.search("/html/body/div/div[2]/div[2]/div/div[2]/div/div[2]/div/h3/a").first.attribute("href")
end
row['selexyz'] = 'http://www.selexyz.nl' + selexyz
# puts selexyz
# Even pauzeren voor verder zoeken, anders gaat bol.com op slot
i = rand(10) + rand + 5
sleep(i)
end
# Resultaten wegschrijven
@csv = table.to_csv(:col_sep => ";")
File.open("aangevuld_isbn.csv", "a") {|f| f.write(@csv) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment