2011-12-04 14 views
11

Il mio livello Python è Novizio. Non ho mai scritto un web scraper o crawler. Ho scritto un codice Python per connettermi ad un API ed estrarre i dati che voglio. Ma per alcuni dati estratti voglio ottenere il sesso dell'autore. Ho trovato questo sito web http://bookblog.net/gender/genie.php, ma lo svantaggio è che non esiste una API disponibile. Mi chiedevo come scrivere un python per inviare dati al modulo nella pagina ed estrarre i dati di ritorno. Sarebbe di grande aiuto se potessi avere una guida su questo.Invia dati tramite modulo web ed estrai i risultati

Questa è 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> 

risultati pagina dom:

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

risposta

22

Non è necessario utilizzare mechanize, è sufficiente inviare i dati del modulo corretti in una richiesta POST.

Inoltre, l'uso di espressioni regolari per analizzare HTML è una cattiva idea. Faresti meglio a usare un parser HTML come 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

ho provato a fare easy_install lxml.html ma ottenendo il seguente errore easy_install lxml.html Ricerca lxml.html Lettura http://pypi.python.org/simple/lxml .html/ Impossibile trovare la pagina di indice per "lxml.html" (forse errata?) Indice di scansione di tutti i pacchetti (potrebbe richiedere un po 'di tempo) Lettura http://pypi.python.org/simple/ No pacchetti locali o collegamenti di download trovati per lxml.html errore: Impossibile trovare la distribuzione adatta per Requirement.parse ('lxml.html') –

+1

In un modulo di importazione, se due nomi hanno un '.' tra di essi, significa che il il secondo nome è all'interno del nome precedente. Il modulo che vuoi installare è lxml. – Acorn

+0

grazie l'ho capito dopo aver inserito il commento. Grazie agianl –

1

È possibile utilizzare mechanize, vedere examples per i dettagli.

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

Grazie mille per la risposta. sembra che machanize sia un modulo che ho installato? rapidamente testato sul terminale ha ottenuto l'errore modulo non. Non sono un mac, dovrei essere in grado di fare easy_install per ottenere machanize. –

+0

Oh, giusto, è un modulo esterno. Sì, puoi eseguire easy_install mechanize. –

15

È possibile utilizzare mechanize per inviare e recuperare il contenuto, e il modulo re per ottenere quello che vuoi. Ad esempio, lo script seguente lo fa per il testo della tua stessa domanda:

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] 

Che cosa fa? Esso crea un mechanize.Browser e va all'URL data:

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

Poi si seleziona la forma (in quanto non v'è un solo modulo da riempire, sarà il primo):

browser.select_form(nr=0) 

Inoltre, imposta le voci del modulo ...

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

... e inviarlo:

response = browser.submit() 

Ora, otteniamo il risultato:

content = response.read() 

Sappiamo che il risultato è in forma:

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

quindi si crea un'espressione regolare per la corrispondenza e utilizzare re.findall():

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

Ora il risultato è disponibile per l'uso:

print result[0] 
+0

Grazie mille questa è una risposta fantastica per una nuova b come me ottima spiegazione.Vorrei poter invitare più di una volta ..;) –