Domanda

Ecco la forma.La stessa forma esatta appare due volte nella fonte.

<form method="POST" action="/login/?tok=sess">
<input type="text" id="usern" name="username" value="" placeholder="Username"/>
<input type="password" id="passw" name="password" placeholder="Password"/>
<input type="hidden" name="ses_token" value="token"/>
<input id="login" type="submit" name="login" value="Log"/>
</form>
.

Sto ricevendo l'attributo "azione" con questo codice PY

import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//action')
raw_input()
.

Poiché ci sono due forme, stampa entrambi gli attributi

['/login/?session=sess', '/login/?session=sess']
.

Come posso ottenerlo per stampare solo uno?Ho solo bisogno di uno, dal momento che sono la stessa forma esatta.

Ho anche una seconda domanda

Come posso ottenere il valore del token? Sto parlando di questa linea:

 <input type="hidden" name="ses_token" value="token"/>
.

Proverò un codice simile,

import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//value')
raw_input()
.

Tuttavia, poiché è più di un attributo denominato valore, verrà stampato

['', 'token', 'Log In', '', 'token', 'Log In'] # or something close to that
.

Come posso ottenere solo il token?E solo uno?

C'è un modo migliore per farlo?

È stato utile?

Soluzione

Utilizzare find() anziché xpath(), poiché find() restituisce solo la prima partita.

Ecco un esempio in base al codice che hai fornito:

import lxml.html


pagesource = """<form method="POST" action="/login/?session=sess">
<input type="text" id="usern" name="username" value="" placeholder="Username"/>
<input type="password" id="passw" name="password" placeholder="Password"/>
<input type="hidden" name="ses_token" value="token"/>
<input id="login" type="submit" name="login" value="Log In"/>
</form>
<form method="POST" action="/login/?session=sess">
<input type="text" id="usern" name="username" value="" placeholder="Username"/>
<input type="password" id="passw" name="password" placeholder="Password"/>
<input type="hidden" name="ses_token" value="token"/>
<input id="login" type="submit" name="login" value="Log In"/>
</form>
"""

tree = lxml.html.fromstring(pagesource)
form = tree.find('.//form')

print "Action:", form.action
print "Token:", form.find('.//input[@name="ses_token"]').value
.

Stampe:

Action: /login/?session=sess
Token: token
.

Spero che ti aiuti.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top