Python-BeautifulSoup从输入中提取值

时间:2018-09-28 10:10:55

标签: python python-3.x beautifulsoup

我正在尝试从网页中提取CSRFToken。我的代码如下:

from bs4 import BeautifulSoup
import requests

r = requests.get('https://www.clos19.com/en-gb/login')
soup = BeautifulSoup(r.text, 'html.parser')
print(soup.find_all('input', type='hidden'))

来自终端的响应如下:

[<input name="CSRFToken" type="hidden" value="790bf524-642c-4679-a036-8f126fe14940"/>]

如何只输出值790bf524-642c-4679-a036-8f126fe14940?

2 个答案:

答案 0 :(得分:1)

for value in soup.find_all('input', type='hidden'):
    print(value.get('value'))

print(soup.find('input', type='hidden').get('value'))

答案 1 :(得分:1)

这是一个简单的解决方案:

from bs4 import BeautifulSoup
import requests

r = requests.get('https://www.clos19.com/en-gb/login')
soup = BeautifulSoup(r.text, 'html.parser')
print(soup.find('input', type='hidden')["value"])

通过添加[“ value”],打印的输出仅是csrf令牌。