Created
March 7, 2016 23:05
-
-
Save erickgnavar/532ec5743a83e30f0307 to your computer and use it in GitHub Desktop.
Consultar número de seguimiento en Serpost
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
beautifulsoup4==4.4.1 | |
lxml==3.5.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import sys | |
import urllib | |
import urllib2 | |
from datetime import datetime | |
from bs4 import BeautifulSoup | |
url = 'http://clientes.serpost.com.pe/prj_tracking/seguimientolinea.aspx' | |
date_format = '%d/%m/%Y %H:%M' | |
def prepare_post_data(): | |
response = urllib2.urlopen(url) | |
soup = BeautifulSoup(response.read(), 'lxml') | |
form = soup.find('form') | |
data = {} | |
for input_tag in form.find_all('input'): | |
data[input_tag['name']] = input_tag.get('value') | |
return data | |
def query_tracking_code(tracking_code): | |
post_data = prepare_post_data() | |
post_data['txtTracking'] = tracking_code | |
response = urllib2.urlopen(url, urllib.urlencode(post_data)) | |
soup = BeautifulSoup(response.read(), 'lxml') | |
table = soup.find(id='gvSegEnvio') | |
if table is None: | |
return [] | |
result = [] | |
for tr in table.find_all('tr'): | |
tds = tr.find_all('td') | |
if not tds or len(tds) != 2: | |
continue | |
cleaned_date = tds[0].text.strip()[:16] | |
result.append({ | |
'date': datetime.strptime(cleaned_date, date_format), | |
'message': tds[1].text | |
}) | |
return sorted(result, key=lambda x: x['date']) | |
def format_data(data, code): | |
template = '{0:16} | {1:100}' | |
print('Tracking number: {}\n{}'.format(code, '-' * 30)) | |
if not data: | |
print('No result') | |
return | |
for item in data: | |
date = item['date'].strftime(date_format) | |
print(template.format(date, item['message'])) | |
print('\n') | |
if __name__ == '__main__': | |
for code in sys.argv[1:]: | |
format_data(query_tracking_code(code), code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment