python - 捕获具有特定属性的 html 元素
问题描述
我可以从网页中获取以下输入字段:
<input type="hidden" name="csrfmiddlewaretoken" value="CXoeqwAw2LGN5IXGzswnKj2XRu6gCdlfuIAzf3TFH5PhHlRMTaBjVNqIeY3OLaed">
我可以使用以下代码执行此操作:
with requests.Session() as s:
url = 'https://dnsdumpster.com'
response = s.get(url, headers=headers, proxies=proxies)
response.encoding = 'utf-8' # Optional: requests infers this internally
soup = BeautifulSoup(response.text, 'html.parser')
input = soup.find_all('input')
csrfmiddlewaretoken_raw = str(input[0])
print(csrfmiddlewaretoken_raw)
但是,有没有更简单的方法,使用它我可以获得具有 csrfmiddlewaretoken 的“名称”属性的“输入”标签的值。我只是对令牌价值感兴趣。
解决方案
input
使用变量名不好。
只需将其作为字典传递即可。
with requests.Session() as s:
url = 'https://dnsdumpster.com'
response = s.get(url, headers=headers, proxies=proxies)
response.encoding = 'utf-8' # Optional: requests infers this internally
soup = BeautifulSoup(response.text, 'html.parser')
token = soup.find('input',{'name':'csrfmiddlewaretoken'})
print(token['value'])
推荐阅读
- python - 使用 map_partitions 和 pd.df.to_sql 从 dask 数据帧创建 sql 表
- javascript - 如何在javascript jquery中捕获具有相同类名的不同变量中的文本
- c# - 实例化相互引用的对象
- amazon-web-services - 应用程序 ELB 在宽限期之前将流量路由到新添加的实例
- reactjs - 是否可以检测行数据何时折叠或展开
- html - 没有值的 XSL 属性
- sql - 使用 alter 命令在数据库级别永久关闭 ANSI_WARNINGS 不起作用
- java - 如何使用拖动器 2 创建一个带有模拟数据的单例类?
- python - python中的加密货币相关性,使用字典
- c# - 如何使用反射将类型对象转换为 C# 中的列表。我可以访问对象中的属性,但不能访问值,有什么建议吗?