module MetaParser
require 'open-uri'
COMMON_USER_AGENTS = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36','Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36']
def self.parse_doc(url)
Nokogiri::HTML.parse(open(url,'User-Agent' => COMMON_USER_AGENTS.sample))
end
module Facebook
def self.get_attributes(url)
attributes = {}
doc = MetaParser.parse_doc(url)
attributes[:url] = url
attributes[:site_name] = doc.at('meta[property="og:site_name"]')['content']
attributes[:title] = doc.at('meta[property="og:title"]')['content']
attributes[:description] = doc.at('meta[property="og:description"]')['content']
attributes[:image] = doc.at('meta[property="og:image"]')['content']
return attributes
end
end # Facebook
module Twitter
def self.get_attributes(url)
attributes = {}
doc = MetaParser.parse_doc(url)
attributes[:url] = url
attributes[:site_name] = doc.at('meta[name="twitter:site"]')['content']
attributes[:title] = doc.at('meta[name="twitter:title"]')['content']
attributes[:description] = doc.at('meta[name="twitter:description"]')['content']
attributes[:image] = doc.at('meta[name="twitter:image"]')['content']
return attributes
end
end # Twitter
end
사용법 :
MetaParser :: Facebook.get_attributes (" google.com ") MetaParser :: Twitter.get_attributes ("google.com ")
페이지의 소스 코드를 읽고"og : image "속성을 사용하여 meta 함수의 내용을 검색하고 추출합니다 (문자열 함수 사용). , 정규 표현식 또는 DOM 메소드. Btw., 당신이 언급 한 페이지는 디버그 툴의 출력이 명시 적으로 말했듯이이 태그를 가지고있다. – CBroe
감사합니다. @CBroe. 네가 맞다. 내가 제시 한 예에서, 페이스 북은 이미지를 "유추"한다. 페이지의 소스 코드를 읽으려면 어떻게해야합니까? 이 기능을 구현하기 위해 참조 할 수있는 리소스가 있습니까? 나는 전에 그것을 한 적이 없다. – umezo
_ "HTTP (GET) 요청을 작성하여 페이지의 소스 코드를 읽는 방법은?"_ _ 그리고 예, 멋진 리소스를 알고 있습니다. _Google_이라고합니다 ... – CBroe