python - 使用带有xpath语法的lxml.html解析html表单

use*_*332 2 html python xpath lxml.html

这是表格.相同的确切形式在源中出现两次.

<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>
Run Code Online (Sandbox Code Playgroud)

我正在使用此py代码获取"action"属性

import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//action')
raw_input()
Run Code Online (Sandbox Code Playgroud)

由于有两种形式,它会打印两个属性

['/login/?session=sess', '/login/?session=sess']
Run Code Online (Sandbox Code Playgroud)

我如何才能打印一张?我只需要一个,因为它们是完全相同的形式.

我还有第二个问题

我怎样才能获得令牌的价值?我在谈论这一行:

 <input type="hidden" name="ses_token" value="token"/>
Run Code Online (Sandbox Code Playgroud)

我尝试类似的代码,

import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//value')
raw_input()
Run Code Online (Sandbox Code Playgroud)

但是,由于有多个属性名为value,因此会打印出来

['', 'token', 'Log In', '', 'token', 'Log In'] # or something close to that
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得令牌?只有一个?

有一个更好的方法吗?

ale*_*cxe 5

使用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
Run Code Online (Sandbox Code Playgroud)

打印:

Action: /login/?session=sess
Token: token
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.