【问题标题】:Can't get value when try parsing dom尝试解析dom时无法获得价值
【发布时间】:2014-08-12 17:38:30
【问题描述】:
<div class="_5xu4">
  <header class="_5tkh">
    <h3 class="_52jd _52ja _52jg _5f43">CEO in 
       <strong><a href="*****">Magento</a></strong>
    </h3>
  </header>
</div>

def find_specialty(id)
    agent = Mechanize.new
    agent.cookie_jar.load("sessions/"+self.id.to_s)
    agent.get("****")
    profession = []
    agent.page.search("h3").each do |link|
      profession.push(link.text)
    end
    return profession
  end

我想得到CEO in

【问题讨论】:

    标签: ruby nokogiri mechanize


    【解决方案1】:
    require 'nokogiri'
    
    def get_profession(html)
      doc = Nokogiri::HTML(html)
      doc.xpath('//h3/text()').to_s.strip
    end
    
    html_str = <<-__HERE__
      <div class="_5xu4">
        <header class="_5tkh">
          <h3 class="_52jd _52ja _52jg _5f43">CEO in 
             <strong><a href="*****">Magento</a></strong>
          </h3>
        </header>
      </div>
    __HERE__
    
    puts get_profession(html_str) # => "CEO in"
    

    【讨论】:

    • @pguardiario:哎呀,没错!我切换到 Nokogiri HTML 等价物。
    猜你喜欢
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多