How to make a POST request in Python?

5

I would like to know how to make a request POST at this URL , for later get here on this page .

Where do I have to spend the year on the div of the unsigned fiscal body.

    
asked by anonymous 01.04.2015 / 15:33

1 answer

5

There are several ways to do this what you want, the most common are using the urllib , httplib (in Python 3 is http.client ) or requests .

The page that you want to make the request, apparently receives two parameters, ano and entrar . One way to do this with the urllib module is:

def funcao(url, ano):
    parametros = urllib.urlencode({'ano': ano, 'entrar': 'Buscar'})
    html = urllib.urlopen(url, parametros).read()
    return html

To get the result do the following:

url  = "http://venus.maringa.pr.gov.br/arquivos/orgao_oficial/paginar_orgao_oficial_ano.php"
ano  = 2015
html = funcao(url, ano)
print (html)

To extract information from this HTML you can use regular expressions or a parser, for the latter you can use the Beautiful Soup , example:

soup = BeautifulSoup(html)
# Extrai todos os links do elemento a
for link in soup.findAll('a'):
    print(link.get('href'))

Complete example:

import urllib
from BeautifulSoup import BeautifulSoup # Ou: from bs4 import BeautifulSoup

def funcao(url, ano):
    parametros = urllib.urlencode({'ano': ano, 'entrar': 'Buscar'})
    html = urllib.urlopen(url, parametros).read()
    return html

url  = "http://venus.maringa.pr.gov.br/arquivos/orgao_oficial/paginar_orgao_oficial_ano.php"
ano  = 2015
html = funcao(url, ano)
soup = BeautifulSoup(html)

for link in soup.findAll('a'):
    print(link.get('href'))
02.04.2015 / 00:40