【发布时间】:2018-08-05 05:46:53
【问题描述】:
你会通过一系列问题看到我已经建立了一个小机械化任务来访问页面()找到咖啡馆的链接并将咖啡馆的详细信息保存在 csv 中。
task :estimateone => :environment do
require 'mechanize'
require 'csv'
mechanize = Mechanize.new
mechanize.history_added = Proc.new { sleep 30.0 }
mechanize.ignore_bad_chunking = true
mechanize.follow_meta_refresh = true
page = mechanize.get('http://www.siteexamplea.com/city/list/50-city-cafes-you-should-have-eaten-breakfast-at')
results = []
results << ['name', 'streetAddress', 'addressLocality', 'postalCode', 'addressRegion', 'addressCountry', 'telephone', 'url']
page.css('ol li a').each do |link|
mechanize.click(link)
name = mechanize.page.css('article h1[itemprop="name"]').text.strip
streetAddress = mechanize.page.css('address span span[itemprop="streetAddress"]').text.strip
addressLocality = mechanize.page.css('address span span[itemprop="addressLocality"]').text.strip
postalCode = mechanize.page.css('address span span[itemprop="postalCode"]').text.strip
addressRegion = mechanize.page.css('address span span[itemprop="addressRegion"]').text.strip
addressCountry = mechanize.page.css('address span meta[itemprop="addressCountry"]').text.strip
telephone = mechanize.page.css('address span[itemprop="telephone"]').text.strip
url = mechanize.page.css('article p a[itemprop="url"]').text.strip
tags = mechanize.page.css('article h1[itemprop="name"]').text.strip
results << [name, streetAddress, addressLocality, postalCode, addressRegion, addressCountry, telephone, url]
end
CSV.open("filename.csv", "w+") do |csv_file|
results.each do |row|
csv_file << row
end
end
end
当我到达第十个链接时,我遇到了 503 错误。
Mechanize::ResponseCodeError: 503 => Net::HTTPServiceUnavailable for https://www.city.com/city/directory/morning-after -- unhandled response
我已经尝试了一些方法来阻止这种情况的发生或从这种状态中解救出来,但我无法解决。有什么建议吗?
【问题讨论】:
-
尝试检查 Mechanize::ResponseCodeError,如果是 50x,则添加 x 时间等待并重试。或者您可以尝试为每个要访问的网址添加一些延迟。
-
@SebastianPalma 不是 mechanize.history_added = Proc.new { sleep 30.0 } 在做什么吗?
-
503 是服务器错误。服务器不喜欢您的请求。尝试在浏览器中发出该请求,看看会发生什么。另外,请研究调试代理,如 Fiddler 或 Charles。
-
@pguardiario 感谢队友,该网址确实有效,因此我将查看 Fiddler 或 Charles