Class: Brand2csv::Swissreg
- Inherits:
-
Object
- Object
- Brand2csv::Swissreg
- Defined in:
- lib/brand2csv.rb
Defined Under Namespace
Classes: Vereinfachte
Constant Summary collapse
- BekannteFehler =
Weitere gesehene Fehler
['Das Datum ist ung', # ültig' '500 Internal Server Error', 'Vereinfachte Trefferliste anzeigen', 'Es wurden keine Daten gefunden.', 'Die Suchkriterien sind teilweise unzul', # ässig', 'Geben Sie mindestens ein Suchkriterium ein', 'Die Suche wurde abgebrochen, da die maximale Suchzeit von 60 Sekunden', 'Erweiterte Suche', ]
- Base_uri =
'https://www.swissreg.ch'- Start_uri =
"#{Base_uri}/srclient/faces/jsp/start.jsp"- Sr1 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr1.jsp"- Sr2 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr2.jsp"- Sr3 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr3.jsp"- Sr30 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr30.jsp"- Sr300 =
"#{Base_uri}/srclient/faces/jsp/trademark/sr300.jsp"- DetailRegexp =
/d_swissreg:mainContent:data:(\d*):tm_no_detail:id_detail/i- AddressRegexp =
/^(\d\d\d\d)\W*(.*)/- LineSplit =
', '- DefaultCountry =
'Schweiz'- TMChoiceFields =
Angezeigte Spalten “id_swissreg:mainContent:id_ckbTMChoice”
[ "tm_lbl_tm_text", # Marke # "tm_lbl_state"], # Status # "tm_lbl_nizza_class"], # Nizza Klassifikation Nr. # "tm_lbl_no"], # disabled="disabled"], # Nummer "tm_lbl_applicant", # Inhaber/in "tm_lbl_country", # Land (Inhaber/in) # "tm_lbl_agent", # Vertreter/in # "tm_lbl_licensee"], # Lizenznehmer/in "tm_lbl_app_date", # Hinterlegungsdatum ]
- MaxZeilen =
5- HitsPerPage =
250- LogDir =
'log'- UseClick =
false
Instance Attribute Summary collapse
-
#marke ⇒ Object
Returns the value of attribute marke.
-
#results ⇒ Object
Returns the value of attribute results.
-
#timespan ⇒ Object
Returns the value of attribute timespan.
Class Method Summary collapse
- .emitCsv(results, filename = 'ausgabe.csv') ⇒ Object
-
.getInputValuesFromPage(body) ⇒ Object
body of HTML page.
- .getMarkenInfoFromDetail(doc) ⇒ Object
- .getTrademarkNumbers(doc) ⇒ Object
-
.inputValue(values, key) ⇒ Object
return value of an array of POST values.
-
.parseAddress(number, inhaber) ⇒ Object
the number is only passed to facilitate debugging lines are the address lines.
- .setAllInputValue(form, values) ⇒ Object
-
.setInputValue(values, key, newValue) ⇒ Object
set value for a key of an array of POST values.
Instance Method Summary collapse
- #checkErrors(body, exitIfFailure = true) ⇒ Object
-
#fetchDetails(nummer) ⇒ Object
takes a long time!.
- #fetchresult(filename = "#{LogDir}/fetch_1.html", counter = 1) ⇒ Object
- #getAllHits(filename = nil, pageNr = 1) ⇒ Object
-
#init_swissreg ⇒ Object
Initialize a session with swissreg and save the cookie as @state.
-
#initialize(timespan, marke = nil) ⇒ Swissreg
constructor
A new instance of Swissreg.
-
#parse_swissreg(timespan = @timespan, marke = @marke, nummer = @number) ⇒ Object
sollte 377 Treffer ergeben, für 01.06.2007-10.06.2007, 559271 wurde in diesem Zeitraum registriert.
- #writeResponse(filename) ⇒ Object
Constructor Details
#initialize(timespan, marke = nil) ⇒ Swissreg
Returns a new instance of Swissreg.
92 93 94 95 96 97 98 99 100 101 |
# File 'lib/brand2csv.rb', line 92 def initialize(timespan, marke = nil) @timespan = timespan @marke = marke @number = nil @results = [] @all_trademark_numbers = [] @errors = Hash.new @lastDetail =nil @counterDetails = 0 end |
Instance Attribute Details
#marke ⇒ Object
Returns the value of attribute marke.
90 91 92 |
# File 'lib/brand2csv.rb', line 90 def marke @marke end |
#results ⇒ Object
Returns the value of attribute results.
90 91 92 |
# File 'lib/brand2csv.rb', line 90 def results @results end |
#timespan ⇒ Object
Returns the value of attribute timespan.
90 91 92 |
# File 'lib/brand2csv.rb', line 90 def timespan @timespan end |
Class Method Details
.emitCsv(results, filename = 'ausgabe.csv') ⇒ Object
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
# File 'lib/brand2csv.rb', line 353 def Swissreg::emitCsv(results, filename='ausgabe.csv') return if results == nil or results.size == 0 if /^1\.8/.match(RUBY_VERSION) ausgabe = File.open(filename, 'w+') # Write header s='' results[0].members.each { |member| s += member + ';' } ausgabe.puts s.chop # write all line results.each{ |result| s = '' result.members.each{ |member| unless eval("result.#{member}") s += ';' else value = eval("result.#{member.to_s}") value = "\"#{value}\"" if value.index(';') s += value + ';' end } ausgabe.puts s.chop } ausgabe.close else CSV.open(filename, 'w', :headers=>results[0].members, :write_headers => true, :col_sep => ';' ) do |csv| results.each{ |x| csv << x } end end end |
.getInputValuesFromPage(body) ⇒ Object
body of HTML page
268 269 270 271 272 273 274 275 |
# File 'lib/brand2csv.rb', line 268 def Swissreg::getInputValuesFromPage(body) # body of HTML page contentData = [] body.search('input').each{ |input| # puts "name: #{input.attribute('name')} value #{input.attribute('value')}" contentData << [ input.attribute('name').to_s, input.attribute('value').to_s ] } contentData end |
.getMarkenInfoFromDetail(doc) ⇒ Object
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
# File 'lib/brand2csv.rb', line 306 def Swissreg::getMarkenInfoFromDetail(doc) marke = nil number = 'invalid' bezeichnung = nil inhaber = nil hinterlegungsdatum = nil doc.xpath("//html/body/form/div/div/fieldset/div/table/tbody/tr").each{ |x| if x.children.first.text.eql?('Marke') if x.children[1].text.index('Markenabbildung') # we must fetch the link to the image bezeichnung = x.children[1].elements.first.attribute('href').text else # we got a trademark bezeichnung = x.children[1].text end end if x.children.first.text.eql?('Inhaber/in') inhaber = />(.*)<\/td/.match(x.children[1].to_s)[1].gsub('<br>',LineSplit) end hinterlegungsdatum = x.children[1].text if x.children.first.text.eql?('Hinterlegungsdatum') number = x.children[1].text if x.children.first.text.eql?('Gesuch Nr.') } zeile_1, zeile_2, zeile_3, zeile_4, zeile_5, plz, ort = Swissreg::parseAddress(number, inhaber) marke = Marke.new(bezeichnung, number, inhaber, DefaultCountry, hinterlegungsdatum, zeile_1, zeile_2, zeile_3, zeile_4, zeile_5, plz, ort ) end |
.getTrademarkNumbers(doc) ⇒ Object
387 388 389 390 391 392 393 394 395 396 |
# File 'lib/brand2csv.rb', line 387 def Swissreg::getTrademarkNumbers(doc) trademark_numbers = [] doc.search('a').each{ |link| if DetailRegexp.match(link.attribute('id')) trademark_numbers << link.children.first.children.first.content end } trademark_numbers end |
.inputValue(values, key) ⇒ Object
return value of an array of POST values
278 279 280 281 282 283 |
# File 'lib/brand2csv.rb', line 278 def Swissreg::inputValue(values, key) values.each{ |val| return val[1] if key.eql?(val[0]) } return nil end |
.parseAddress(number, inhaber) ⇒ Object
the number is only passed to facilitate debugging lines are the address lines
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
# File 'lib/brand2csv.rb', line 227 def Swissreg::parseAddress(number, inhaber) lines = CGI.unescapeHTML(inhaber).split(LineSplit) ort = nil plz = nil # Search for plz/address 1.upto(lines.length-1).each { |cnt| if m = AddressRegexp.match(lines[cnt]) lines[cnt+1] = nil plz = m[1]; ort = m[2] cnt.upto(MaxZeilen-1).each{ |cnt2| lines[cnt2] = nil } break end } unless plz puts "Achtung! Konnte Marke #{number} mit Inhaber #{lines.inspect} nicht parsen" if $VERBOSE return nil, nil, nil, nil, nil, nil, nil, nil end # search for lines with only digits found = false 1.upto(lines.length-1).each { |cnt| break if lines[cnt] == nil if /^\d*$/.match(lines[cnt]) found = true if lines[cnt+1] == nil found = 'before' lines[cnt-1] += LineSplit + lines[cnt] lines.delete_at(cnt) else found = 'after' lines[cnt] += LineSplit + lines[cnt+1] lines.delete_at(cnt+1) end end } puts "found #{found}: #{lines.inspect}" if found and $VERBOSE return lines[0], lines[1], lines[2], lines[3], lines[4], plz, ort end |
.setAllInputValue(form, values) ⇒ Object
296 297 298 299 300 301 302 303 304 |
# File 'lib/brand2csv.rb', line 296 def Swissreg::setAllInputValue(form, values) values.each{ |newValue| # puts "x: 0 #{ newValue[0].to_s} 1 #{newValue[1].to_s}" form.field(:name => newValue[0].to_s) { |elem| next if elem == nil # puts "Cannot set #{newValue[0].to_s}" elem.value = newValue[1].to_s } } end |
.setInputValue(values, key, newValue) ⇒ Object
set value for a key of an array of POST values
286 287 288 289 290 291 292 293 294 |
# File 'lib/brand2csv.rb', line 286 def Swissreg::setInputValue(values, key, newValue) values.each{ |val| if key.eql?(val[0]) val[1] = newValue return end } return end |
Instance Method Details
#checkErrors(body, exitIfFailure = true) ⇒ Object
113 114 115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/brand2csv.rb', line 113 def checkErrors(body, exitIfFailure = true) BekannteFehler.each { |errMsg| if body.to_s.index(errMsg) if exitIfFailure puts "Tut mir leid. Suche wurde mit Fehlermeldung <#{errMsg}> abgebrochen." exit 2 else puts "Info: Suche meldet <#{errMsg}> " end end } end |
#fetchDetails(nummer) ⇒ Object
takes a long time!
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
# File 'lib/brand2csv.rb', line 333 def fetchDetails(nummer) # takes a long time! @counterDetails += 1 init_swissreg if @counterDetails % 90 == 0 # it seems that swissreg is artificially slowing down serving request after 100 hits filename = "#{LogDir}/detail_#{sprintf('%05d', @counterDetails)}_#{nummer.gsub('/','.')}.html" if File.exists?(filename) doc = Nokogiri::Slop(File.open(filename)) else url = "#{Sr300}?language=de§ion=tm&id=#{nummer}" pp "#{Time.now.strftime("%H:%M:%S")}: Opening #{filename}" if $VERBOSE $stdout.flush content = @agent.get_file url body = @agent.page.body body.force_encoding('utf-8') unless /^1\.8/.match(RUBY_VERSION) doc = Nokogiri::Slop(body) writeResponse(filename) end marke = Swissreg::getMarkenInfoFromDetail(doc) @results << marke end |
#fetchresult(filename = "#{LogDir}/fetch_1.html", counter = 1) ⇒ Object
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 |
# File 'lib/brand2csv.rb', line 493 def fetchresult(filename = "#{LogDir}/fetch_1.html", counter = 1) if filename && File.exists?(filename) doc = Nokogiri::Slop(File.open(filename)) else body = @agent.page.body body.force_encoding('utf-8') unless /^1\.8/.match(RUBY_VERSION) doc = Nokogiri::Slop(body) writeResponse(filename) end if /Vereinfachte Trefferliste anzeigen/i.match(doc.text) form = @agent.page.forms.first = form.(:value => /Vereinfachte/i) # submit the form using that button @agent.submit(form, ) filename = "#{LogDir}/vereinfacht.html" writeResponse(filename) end getAllHits(doc, counter) puts"getAllHits: returned #{@all_trademark_numbers ? @all_trademark_numbers.size : 0} hits " if @all_trademark_numbers @all_trademark_numbers.each{ |nr| nrRetries = 0 begin fetchDetails(nr) rescue Exception => e nrRetries += 1 puts e.backtrace puts "fetchDetails did not work reinit session and retry for #{nr}. nrRetries #{nrRetries}/3. e #{e}" if nrRetries <= 3 init_swissreg retry else raise Interrupt end end } else puts "Could not find any trademarks in #{filename}" end end |
#getAllHits(filename = nil, pageNr = 1) ⇒ Object
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
# File 'lib/brand2csv.rb', line 461 def getAllHits(filename = nil, pageNr = 1) if filename && File.exists?(filename) doc = Nokogiri::Slop(File.open(filename)) else body = @agent.page.body body.force_encoding('utf-8') unless /^1\.8/.match(RUBY_VERSION) doc = Nokogiri::Slop(body) filename = "#{LogDir}/vereinfachte_#{pageNr}.html" writeResponse(filename) end einfach = Swissreg::Vereinfachte.new(doc) puts "#{Time.now.strftime("%H:%M:%S")} status: getAllHits for #{pageNr} of #{einfach.nrSubPages} pages" if $VERBOSE subPage2Fetch = pageNr + 1 data2 = einfach.getPostDataForSubpage(subPage2Fetch).clone if (HitsPerPage < einfach.nrHits - einfach.firstHit) itemsToFetch = HitsPerPage else itemsToFetch = einfach.nrHits - einfach.firstHit end @all_trademark_numbers += Swissreg::getTrademarkNumbers(doc) filename = "#{LogDir}/vereinfachte_#{pageNr}_back.html" writeResponse(filename) if pageNr < (einfach.nrSubPages) Swissreg::setAllInputValue(@agent.page.forms.first, data2) @agent.page.forms.first.submit getAllHits(nil, subPage2Fetch) end @all_trademark_numbers end |
#init_swissreg ⇒ Object
Initialize a session with swissreg and save the cookie as @state
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/brand2csv.rb', line 130 def init_swissreg begin @agent = Mechanize.new { |agent| agent.user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0' agent.verify_mode = OpenSSL::SSL::VERIFY_NONE FileUtils.makedirs(LogDir) if $VERBOSE or defined?(RSpec) agent.log = Logger.new("#{LogDir}/mechanize.log") if $VERBOSE } @agent.get_file Start_uri # 'https://www.swissreg.ch/srclient/faces/jsp/start.jsp' writeResponse("#{LogDir}/session_expired.html") checkErrors(@agent.page.body, false) @agent.page.links[3].click writeResponse("#{LogDir}/homepage.html") @state = @agent.page.form["javax.faces.ViewState"] rescue Net::HTTPInternalServerError, Mechanize::ResponseCodeError puts "Net::HTTPInternalServerError oder Mechanize::ResponseCodeError gesehen.\n #{Base_uri} hat wahrscheinlich Probleme" exit 3 end end |
#parse_swissreg(timespan = @timespan, marke = @marke, nummer = @number) ⇒ Object
sollte 377 Treffer ergeben, für 01.06.2007-10.06.2007, 559271 wurde in diesem Zeitraum registriert
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
# File 'lib/brand2csv.rb', line 150 def parse_swissreg(timespan = @timespan, # sollte 377 Treffer ergeben, für 01.06.2007-10.06.2007, 559271 wurde in diesem Zeitraum registriert marke = @marke, nummer =@number) # nummer = "559271" ergibt genau einen treffer init_swissreg data = [ ["autoScroll", "0,0"], ["id_swissreg:_link_hidden_", ""], ["id_swissreg_SUBMIT", "1"], ["id_swissreg:_idcl", "id_swissreg_sub_nav_ipiNavigation_item0"], ["javax.faces.ViewState", @state], ] @agent.page.form['id_swissreg:_idcl'] = 'id_swissreg_sub_nav_ipiNavigation_item0' @agent.page.forms.first.submit writeResponse("#{LogDir}/trademark_simple.html") data = [ ["autoScroll", "0,0"], ["id_swissreg:_link_hidden_", ""], ["id_swissreg_SUBMIT", "1"], ["id_swissreg:_idcl", "id_swissreg_sub_nav_ipiNavigation_item0_item3"], ["javax.faces.ViewState", @state], ] @agent.page.form['id_swissreg:_idcl'] = 'id_swissreg_sub_nav_ipiNavigation_item0_item3' @agent.page.forms.first.submit writeResponse("#{LogDir}/trademark_extended.html") data = [ ["autoScroll", "0,829"], ["id_swissreg:_link_hidden_", ""], ["id_swissreg:mainContent:id_ckbTMState", "1"], # Hängige Gesuche 1 ["id_swissreg:mainContent:id_ckbTMState", "3"], # Aktive Marken 3 ["id_swissreg:mainContent:id_txf_tm_no", ""],# Marken Nr ["id_swissreg:mainContent:id_txf_app_no", ""], # Gesuch Nr. ["id_swissreg:mainContent:id_txf_tm_text", "#{marke}"], ["id_swissreg:mainContent:id_txf_applicant", ""], # Inhaber/in ["id_swissreg:mainContent:id_cbxCountry", '_ALL'], ["id_swissreg:mainContent:id_txf_agent", ""], # Vertreter/in ["id_swissreg:mainContent:id_txf_licensee", ""], # Lizenznehmer ["id_swissreg:mainContent:id_txf_nizza_class", ""], # Nizza Klassifikation Nr. ["id_swissreg:mainContent:id_txf_appDate", "#{timespan}"] , ["id_swissreg:mainContent:id_txf_expiryDate", ""], # Ablauf Schutzfrist ["id_swissreg:mainContent:id_cbxTMTypeGrp", "_ALL"], # Markenart ["id_swissreg:mainContent:id_cbxTMForm", "_ALL"], # Markentyp ["id_swissreg:mainContent:id_cbxTMColorClaim", "_ALL"], # Farbanspruch ["id_swissreg:mainContent:id_txf_pub_date", ""], # Publikationsdatum ["id_swissreg:mainContent:id_ckbTMPubReason", '1'], ["id_swissreg:mainContent:id_ckbTMPubReason", '2'], ["id_swissreg:mainContent:id_ckbTMPubReason", '3'], ["id_swissreg:mainContent:id_ckbTMPubReason", '4'], ["id_swissreg:mainContent:id_ckbTMPubReason", '5'], ["id_swissreg:mainContent:id_ckbTMPubReason", '6'], ["id_swissreg:mainContent:id_ckbTMPubReason", '7'], ["id_swissreg:mainContent:id_ckbTMPubReason", '8'], ["id_swissreg:mainContent:id_cbxFormatChoice", "1"], ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_tm_text"], ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_applicant"], ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_country"], ["id_swissreg:mainContent:id_ckbTMChoice", "tm_lbl_app_date"], ["id_swissreg:mainContent:id_cbxHitsPerPage", HitsPerPage], # Treffer pro Seite ["id_swissreg:mainContent:sub_fieldset:id_submit", "suchen"], ["id_swissreg_SUBMIT", "1"], ["id_swissreg:_idcl", ""], ["id_swissreg:_link_hidden_", ""], ["javax.faces.ViewState", @state], ] begin @agent.post(Sr3, data) rescue Timeout::Error puts "Timeout!" retry end writeResponse("#{LogDir}/first_results.html") checkErrors(@agent.page.body, false) end |
#writeResponse(filename) ⇒ Object
103 104 105 106 107 108 109 110 111 |
# File 'lib/brand2csv.rb', line 103 def writeResponse(filename) if defined?(RSpec) or $VERBOSE ausgabe = File.open(filename, 'w+') ausgabe.puts @agent.page.body ausgabe.close else puts "Skipping writing #{filename}" if $VERBOSE end end |