2011-12-04 7 views
11

Mi nivel python es Novato. Nunca he escrito un raspador web o rastreador. He escrito un código python para conectarme a una API y extraer los datos que deseo. Pero para algunos de los datos extraídos, quiero obtener el género del autor. Encontré este sitio web http://bookblog.net/gender/genie.php, pero a la baja hay una aplicación disponible. Me preguntaba cómo escribir un pitón para enviar datos al formulario en la página y extraer los datos de retorno. Sería de gran ayuda si pudiera obtener alguna orientación sobre esto.Presentar datos a través del formulario web y extraer los resultados

Ésta es la forma dom:

<form action="analysis.php" method="POST"> 
<textarea cols="75" rows="13" name="text"></textarea> 
<div class="copyright">(NOTE: The genie works best on texts of more than 500 words.)</div> 
<p> 
<b>Genre:</b> 
<input type="radio" value="fiction" name="genre"> 
fiction&nbsp;&nbsp; 
<input type="radio" value="nonfiction" name="genre"> 
nonfiction&nbsp;&nbsp; 
<input type="radio" value="blog" name="genre"> 
blog entry 
</p> 
<p> 
</form> 

resultados página dom:

<p> 
<b>The Gender Genie thinks the author of this passage is:</b> 
male! 
</p> 

Respuesta

22

No necesita usar mecanizar, solo envíe los datos de formulario correctos en una solicitud POST.

Además, el uso de expresiones regulares para analizar HTML es una mala idea. Sería mejor utilizar un analizador HTML como lxml.html.

import requests 
import lxml.html as lh 


def gender_genie(text, genre): 
    url = 'http://bookblog.net/gender/analysis.php' 
    caption = 'The Gender Genie thinks the author of this passage is:' 

    form_data = { 
     'text': text, 
     'genre': genre, 
     'submit': 'submit', 
    } 

    response = requests.post(url, data=form_data) 

    tree = lh.document_fromstring(response.content) 

    return tree.xpath("//b[text()=$caption]", caption=caption)[0].tail.strip() 


if __name__ == '__main__': 
    print gender_genie('I have a beard!', 'blog') 
+0

intenté hacer easy_install lxml.html pero obteniendo el siguiente error easy_install lxml.html Buscando lxml.html Leyendo http://pypi.python.org/simple/lxml .html/ No se pudo encontrar la página de índice para 'lxml.html' (¿quizás mal escrito?) Índice de escaneo de todos los paquetes (esto puede llevar un tiempo) Lectura http://pypi.python.org/simple/ No paquetes locales o enlaces de descarga encontrados para lxml.html error: No se pudo encontrar la distribución adecuada para Requirement.parse ('lxml.html') –

+1

En una importación de módulo, si dos nombres tienen un '.' entre ellos, significa que el el segundo nombre está dentro del nombre anterior. El módulo que desea instalar es lxml. – Acorn

+0

gracias me di cuenta después de poner el comentario. Gracias agianl –

1

Usted puede utilizar mechanize, ver examples para más detalles.

from mechanize import ParseResponse, urlopen, urljoin 

uri = "http://bookblog.net" 

response = urlopen(urljoin(uri, "/gender/genie.php")) 
forms = ParseResponse(response, backwards_compat=False) 
form = forms[0] 

#print form 

form['text'] = 'cheese' 
form['genre'] = ['fiction'] 

print urlopen(form.click()).read() 
+0

Muchas gracias por la respuesta. suena como machanize es un módulo que tengo instalado? probado rápidamente en el terminal obtuvo el error sin módulo. No soy un Mac, debería ser capaz de hacer easy_install para obtener machanize. –

+0

Oh, correcto, es un módulo externo. Sí, puedes hacer easy_install mecanizar. –

15

Puede utilizar mechanize a presentar y recuperar el contenido, y el módulo de re para conseguir lo que desea. Por ejemplo, el siguiente script lo hace por el texto de su propia pregunta:

import re 
from mechanize import Browser 

text = """ 
My python level is Novice. I have never written a web scraper 
or crawler. I have written a python code to connect to an api and 
extract the data that I want. But for some the extracted data I want to 
get the gender of the author. I found this web site 
http://bookblog.net/gender/genie.php but downside is there isn't an api 
available. I was wondering how to write a python to submit data to the 
form in the page and extract the return data. It would be a great help 
if I could get some guidance on this.""" 

browser = Browser() 
browser.open("http://bookblog.net/gender/genie.php") 

browser.select_form(nr=0) 
browser['text'] = text 
browser['genre'] = ['nonfiction'] 

response = browser.submit() 

content = response.read() 

result = re.findall(
    r'<b>The Gender Genie thinks the author of this passage is:</b> (\w*)!', content) 

print result[0] 

¿Qué hacer? Se crea una mechanize.Browser y va a la URL dada:

browser = Browser() 
browser.open("http://bookblog.net/gender/genie.php") 

Luego se selecciona la forma (ya que sólo hay un formulario para ser llenado, será el primero):

browser.select_form(nr=0) 

Además, que establece las entradas de la forma ...

browser['text'] = text 
browser['genre'] = ['nonfiction'] 

... y presentarlo:

response = browser.submit() 

Ahora, obtenemos el resultado:

content = response.read() 

Sabemos que el resultado es en la forma:

<b>The Gender Genie thinks the author of this passage is:</b> male! 

Así se crea una expresión regular para coincidir y utilizar re.findall():

result = re.findall(
    r'<b>The Gender Genie thinks the author of this passage is:</b> (\w*)!', 
    content) 

Ahora el resultado está disponible para su uso:

print result[0] 
+0

Muchas gracias esta es una respuesta fantástica para una nueva b como yo gran explicación.Desearía poder votar más de una vez ...;) –

Cuestiones relacionadas