Python - XPath 구문을 사용하여 lxml.html로 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>
.
이 PY 코드
에서 "조치"속성을 얻고 있습니다.import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//action')
raw_input()
.
두 가지 형태가 있으므로 모두 속성을 모두 인쇄합니다
['/login/?session=sess', '/login/?session=sess']
.
어떻게 그냥 인쇄 할 수 있습니까?나는 그것이 동일한 정확한 형태이기 때문에 나는 단지 하나만 필요합니다.
두 번째 질문이 있습니다
토큰의 값을 어떻게 얻을 수 있습니까? 나는이 줄에 대해 이야기하고있다 :
<input type="hidden" name="ses_token" value="token"/>
.
비슷한 코드를 시도합니다.
import lxml.html
tree = lxml.html.fromstring(pagesource)
print tree.xpath('//value')
raw_input()
.
그러나 값이 두 개 이상의 속성이므로
를 인쇄합니다['', '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