【问题标题】:Grabbing the value of a HTML form input field?获取 HTML 表单输入字段的值?
【发布时间】:2019-06-30 18:42:44
【问题描述】:

有一个网页类似于:www.example.com/form.php

我想使用 Python 从页面上的 HTML 表单中获取其中一个值。例如,如果表单有我可以返回值“test”

我已经广泛搜索了这个,但大多数与发布表单数据有关,或者有使用 Django 或 cgi-bin 的建议。我无法直接访问服务器,所以我不能这样做。

我认为库 REQUESTS 可以做到,但我在文档中看不到它。

HTML:

<html>
<body>
<form method="" action="formpost.php" name="form1" id="form1">
<input type="text" name"field1" value="this is field1">
<input type="hidden" name="key" value="secret key field">
</form>
</body>

例如,我希望在 Python 中使用类似的东西:

import special_library

html = special_library.get("http://www.example.com/form.php")
print html.get_field("wanted")

有没有人有任何建议来实现这一目标?或者我可能没有想到或不知道的任何库?

【问题讨论】:

    标签: python python-3.x python-requests urllib


    【解决方案1】:

    您可以使用requests 库和lxml

    试试这个:

    import requests
    from lxml import html
    
    s = requests.Session()
    resp = s.get("http://www.example.com/form.php")
    doc = html.fromstring(resp.text)
    
    wanted_value = doc.xpath("//input[@class='wanted_class_name']/@value")
    print(wanted_value)
    

    您可以查看以下资源:

    【讨论】:

    • 我做到了!这有效:``` import requests import lxml.html s = requests.session() resp = s.get("example.com/myform.php") doc = lxml.html.fromstring(resp.text) form = doc.forms[0] print(form.fields["wanted_text_field"]) ``` 谢谢你的建议,lxml 效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 2010-09-15
    相关资源
    最近更新 更多