首页 > 解决方案 > 捕获具有特定属性的 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 的“名称”属性的“输入”标签的值。我只是对令牌价值感兴趣。

标签: pythonbeautifulsoup

解决方案


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'])

推荐阅读