Module: RetrieveTitle
- Defined in:
- lib/retrieve_title.rb
Constant Summary collapse
- CRAWL_TIMEOUT =
1
Class Method Summary collapse
- .crawl(url, max_redirects: nil, initial_https_redirect_ignore_limit: false) ⇒ Object
- .extract_title(html, encoding = nil) ⇒ Object
Class Method Details
.crawl(url, max_redirects: nil, initial_https_redirect_ignore_limit: false) ⇒ Object
6 7 8 9 10 11 12 13 14 |
# File 'lib/retrieve_title.rb', line 6 def self.crawl(url, max_redirects: nil, initial_https_redirect_ignore_limit: false) fetch_title( url, max_redirects: max_redirects, initial_https_redirect_ignore_limit: initial_https_redirect_ignore_limit, ) rescue Net::ReadTimeout, FinalDestination::SSRFError # do nothing for Net::ReadTimeout errors end |
.extract_title(html, encoding = nil) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/retrieve_title.rb', line 16 def self.extract_title(html, encoding = nil) title = nil return nil if html =~ /<title>/ && html !~ %r{</title>} doc = nil begin doc = Nokogiri.HTML5(html, nil, encoding) rescue ArgumentError # invalid HTML (Eg: too many attributes, status tree too deep) - ignore # Error in nokogumbo is not specialized, uses generic ArgumentError # see: https://www.rubydoc.info/gems/nokogiri/Nokogiri/HTML5#label-Error+reporting end if doc title = doc.at("title")&.inner_text # A horrible hack - YouTube uses `document.title` to populate the title # for some reason. For any other site than YouTube this wouldn't be worth it. if title == "YouTube" && html =~ /document\.title *= *"(.*)";/ title = Regexp.last_match[1].sub(/ - YouTube\z/, "") end if !title && node = doc.at('meta[property="og:title"]') title = node["content"] end end if title.present? title.gsub!(/\n/, " ") title.gsub!(/ +/, " ") title.strip! return title end nil end |