我正在尝试提取隐藏输入标记的值。即使HTML中存在该元素,我在bs4中也找不到它。
这是我得到的错误消息:
AttributeError: 'NoneType' object has no attribute 'find'
这是网页上的html:
<form id="exampleid" class="exampleclass" action="/ex/ex-ex/ex/2" method="post">
<more html>
<div>
<input type="hidden" name="csrf" value="abcdefghijklmnopqrstuvwxyz">
</div></form>
这是我目前的代码:
csrf = soup.find("form", {"id": "exampleid"})
csrf = csrf.find('input', {'name': 'csrf'}).get("value")
print(csrf)
我很感激任何帮助,因为它真的困扰着我。提前谢谢!
您的选择仍然有效,认为还有其他问题,也许您无法获得所需的html。
作为选择和获取此隐藏<input>
的值的替代方案,您可以使用以下css selector
:
soup.select_one('#exampleid input[name*="csrf"]')['value']
示例
from bs4 import BeautifulSoup
html = '''
<form id="exampleid" class="exampleclass" action="/ex/ex-ex/ex/2" method="post">
<div>
<input type="hidden" name="csrf" value="abcdefghijklmnopqrstuvwxyz">
</div></form>'''
soup = BeautifulSoup(html, "lxml")
csrf = soup.select_one('#exampleid input[name*="csrf"]')['value']
print(csrf)
输出
abcdefghijklmnopqrstuvwxyz