[[Ruby]]
なにそれって言われそうだけど ''「IE9以上じゃないとダメっ!」なサイトにアクセスしたい時にUA偽装は不可欠'' なのよね。そして、それがわからないがゆえにわざわざ wget を中で呼んでる人だっているかも。
* 基本 [#k56013a5]
とりあえずやってみたわ。
require 'open-uri'
require 'timeout'
ua = Hash.new
ua["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
ua["Accept-language"] = "ja;q=1.0, en;q=0.5"
begin
timeout(10){
html = open(url,ua) do |f|
charset = f.charset # 文字種別を取得
f.read # htmlを読み込んで変数htmlに渡す
end
}
rescue TimeoutError => e
p e
rescue => e
p e
end
たぶん、urlの後に直接ハッシュで書きこんでもいけそうね。
タイムアウトと組み合わせると、いろいろできるかもしれないわね。~
あ、でも ''net/http 使うなら、そもそもあっちでタイムアウト管理できるから別途timeoutは必要ない'' のかな?
* 進化版 [#jc86d7f7]
データだけ欲しいとか、UA偽装をランダムにしたいとか、いろいろつめこんでみたわ。
require 'nkf'
require 'open-uri'
require 'timeout'
#
class String
def getAgent
s = [
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36" ,
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:30.0) Gecko/20100101 Firefox/30.0"
]
s[rand(s.length)]
end
def iWebGet(i)
html = nil
ua = Hash.new
ua["User-Agent"] = "".getAgent
ua["Accept-language"] = "ja;q=1.0, en;q=0.5"
begin
timeout(i){
html = open(self,ua) do |f|
charset = f.charset # 文字種別を取得
f.read # htmlを読み込んで変数htmlに渡す
end
}
rescue TimeoutError => e
p e
rescue => e
p e
end
html
end
def iDownload(fn,ow) # ow: overwrite(true/false)
html = self.iWebGet(10) # 数字はタイムアウト時間
if html != nil
html = NKF.nkf("-w",html)
if File.exist?(fn) == false || ow == true
File.write(fn,html)
end
end
end
end
うん、こんな感じかしら。
たとえば、ダウンロードしたいならこうね。
"http://192.168.1.10/".iDownload("log.html",true)
データだけが欲しいなら、こう。(数字はタイムアウト)
html = "http://192.168.1.10/".iWebGet(10)
getAgentに好きなブラウザのをいれてみたり、環境変数を追加してみたり、いろいろ楽しんでみてね。