0

我正在尝试创建一个小型 Rails 应用程序,它将解析 FedEx 站点以获取我的跟踪信息。我尝试使用 Nokogiri 解析站点,但似乎站点上的内容是通过 Ajax 加载的,我无法捕获它。

这是我正在测试的代码:

require 'rubygems'
require 'nokogiri'
require 'open-uri'

doc = Nokogiri::HTML(open('https://www.fedex.com/fedextrack/?cntry_code=us&tab=1&tracknums=543433298736'))

doc.xpath('//*[(@id = "destinationDateTime")]').each do |status|
  puts status.content
end

对此的任何帮助都会很棒。

4

3 回答 3

3

解析整个页面是不好的形式。使用使用 FedEx API 的运输/跟踪 gem,例如active_shipping。他们甚至有一个关于跟踪 FedEx 包裹的部分:

fedex = FedEx.new(:login => '999999999', :password => '7777777')
tracking_info = fedex.find_tracking_info('tracking-number', :carrier_code => 'fedex_ground') # Ground package

tracking_info.shipment_events.each do |event|
  puts "#{event.name} at #{event.location.city}, #{event.location.state} on #{event.time}. #{event.message}"
end
于 2013-01-22T20:05:10.583 回答
1
require 'mechanize'
require 'json'

r = Mechanize.new
r.verify_mode = OpenSSL::SSL::VERIFY_NONE

def fedex(r,tracking_number)

    return r.get("https://www.fedex.com/trackingCal/track?data={%22TrackPackagesRequest%22%3A{%22appType%22%3A%22wtrk%22%2C%22uniqueKey%22%3A%22%22%2C%22processingParameters%22%3A{%22anonymousTransaction%22%3Atrue%2C%22clientId%22%3A%22WTRK%22%2C%22returnDetailedErrors%22%3Atrue%2C%22returnLocalizedDateTime%22%3Afalse}%2C%22trackingInfoList%22%3A[{%22trackNumberInfo%22%3A{%22trackingNumber%22%3A%22#{tracking_number}%22%2C%22trackingQualifier%22%3A%22%22%2C%22trackingCarrier%22%3A%22%22}}]}}&action=trackpackages&locale=en_US&format=json&version=99").body

end

puts "Package number 543433298736 is: " + JSON.parse(fedex(r,"543433298736"))["TrackPackagesResponse"]["packageList"][0]["keyStatus"]
# For the "estimated delivery datetime": ["TrackPackagesResponse"]["packageList"][0]["displayEstDeliveryDateTime"]

这段代码完成了工作:-)

于 2013-01-23T16:38:33.933 回答
0

我做了类似的东西..我最终通过 poltergeist 使用了 capybara 和 phantomjs ......很好地处理了 javascript ......

这是我的脚本的一部分:

# -*- encoding : utf-8 -*-

require 'rubygems'
require 'capybara'
require 'capybara/dsl'
require 'capybara/poltergeist'

class MyTest

    include Capybara::DSL

    Capybara.register_driver :poltergeist do |app|
      Capybara::Poltergeist::Driver.new(app, {debug: false})
    end

    Capybara.run_server = false
    Capybara.current_driver = :poltergeist
    Capybara.app_host = 'http://www.example.com'

    def run
        visit('/home/bezirk?bezirk=1212')
        ...
    end
end
MyTest.new.run
于 2013-01-22T20:04:20.813 回答