Python - XPath構文を使用したlxml.htmlを使用したHTMLフォームの解析
質問
これはフォームです。同じ正確な形式がソースで2回表示されます。
<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>
.
このPYコード
の「アクション」属性を取得していますimport lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//action')
raw_input()
.
フォームが2つありますので、両方の属性
を印刷します。['/login/?session=sess', '/login/?session=sess']
.
どうすれば印刷するにはどうすればよいですか。同じ正確な形式であるため、1つだけ必要です。
私は2番目の質問をしています
どのようにトークンの値を取得できますか? 私はこの行について話しています:
<input type="hidden" name="ses_token" value="token"/>
.
私は類似のコードを試してください、
import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//value')
raw_input()
.
しかし、値が1つ以上の属性になっているので、
を印刷します。['', 'token', 'Log In', '', 'token', 'Log In'] # or something close to that
.
どのように私はトークンだけを手に入れることができますか?そしてただ一つだけ?
これを行うためのより良い方法はありますか?
解決
find()
は最初の一致のみを返すため、xpath()
の代わりにfind()
を使用します。
これはあなたが提供したコードに基づく例です:
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
.
印刷:
Action: /login/?session=sess
Token: token
.
助けを願っています。
所属していません StackOverflow