5.2. LWP and GET RequestsThe way you submit form data with LWP depends on whether the form's action is GET or POST. If it's a GET form, you construct a URL with encoded form data (possibly using the $url->query_form( ) method) and call $browser->get( ). If it's a POST form, you call to call $browser->post( ) and pass a reference to an array of form parameters. We cover POST later in this chapter. 5.2.1. GETting Fixed URLsIf you know everything about the GET form ahead of time, and you know everything about what you'd be typing (as if you're always searching on the name "Dulce"), you know the URL! Because the same data from the same GET form always makes for the same URL, you can just hardcode that: $resp = $browser->get( 'http://www.census.gov/cgi-bin/gazetteer?city=Dulce&state=&zip=' ); And if there is a great big URL in which only one thing ever changes, you could just drop in the value, after URL-encoding it:
Note that you should not simply interpolate a raw unencoded value, like this: $resp = $browser->get( 'http://www.census.gov/cgi-bin/gazetteer?city=' . $city . # wrong! '&state=&zip=' ); The problem with doing it that way is that you have no real assurance that $city's value doesn't need URL encoding. You may "know" that no unencoded town name ever needs escaping, but it's better to escape it anyway. If you're piecing together the parts of URLs and you find yourself calling uri_escape more than once per URL, then you should use the next method, query_form, which is simpler for URLs with lots of variable data. 5.2.2. GETting a query_form( ) URLThe tidiest way to submit GET form data is to make a new URI object, then add in the form pairs using the query_form method, before performing a $browser->get($url) request: $url->query_form(name => value, name => value, ...); For example:
Prints: http://www.census.gov/cgi-bin/gazetteer?city=Some+City&state=Some+State&zip=Some+Zip From this, it's easy to write a small program (shown in Example 5-1) to perform a request on this URL and use some simple regexps to extract the data from the HTML. Example 5-1. gazetteer.pl
Then run it from a prompt:
Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|