Python-BeautifulSoup从多个选项中提取值

时间:2018-09-28 21:19:10

标签: python python-3.x beautifulsoup

代码:

from bs4 import BeautifulSoup
import requests

html = '''        <div class="fieldset-content checkout-login__footer">

        <hr class="checkout-login__newsletter-rule">

        <div class="row checkout-login__footer with-info">
            <div class="columns medium-9 checkout-login__subscribtion-container">
                <input type="checkbox" name="subscriptionForms[0]_value" id="emailSignUp">
                        <label for="emailSignUp">
                            I have read the <a href="/en-gb/customer-care/privacy-policy">Privacy Policy</a> and give consent to email me with updates about Clos19, including the latest product releases and special events.<small class="info js-privacy-policy-info hide"> Uncheck this box to opt out</small>
                        </label>
                        <input type="hidden" class="hidden" name="subscriptionForms[0]_type" value="NEWSLETTER" />
                        <input type="hidden" class="hidden" name="subscriptionForms[0]_location" value="CHECKOUT" />
                </div>
            <div class="columns medium-3 small-12">
                <button type="submit" class="button button-primary float-right positive">Continue</button>
                </div>
        </div>
    </div>
<div>
<input type="hidden" name="CSRFToken" value="80f1330a-7a4e-4878-a6ab-710356f47961" /> '''   

soup = BeautifulSoup(html, 'html.parser')
CSRFToken = soup.find('input', type='hidden')["value"]

print(CSRFToken)

我正在尝试打印80f1330a-7a4e-4878-a6ab-710356f47961,但终端机正在返回新闻通讯,因为这是它找到的第一个。

当name =“ CSRFToken”时,如何找到value的值?

1 个答案:

答案 0 :(得分:2)

您可以在name调用中使用find参数:

from bs4 import BeautifulSoup as soup
print(soup(html, 'html.parser').find('input', {'name':"CSRFToken"})['value'])

输出:

80f1330a-7a4e-4878-a6ab-710356f47961