Python美丽的汤刮数据

时间:2017-10-24 13:32:06

标签: python beautifulsoup

我对beautifulsoup很新。

我有一个这样的表格

<form class="addtoshoppingcart" name="addtoshoppingcart" action="/warenkorb/hinzugefuegen">
    <input name="product_id" type="hidden" value="83612">
    <input name="product_bs_id"  type="hidden" value="">
    <input type="hidden" name="amount" type="text" value="1">
    <div class="addToCartErrors"></div>
    <button id="submitAddToCart" name="addToCart" class="button radius action" disabled='disabled' autocomplete="off">
      <span>In den Warenkorb</span>
    </button>
  </form>

如何保护值,即83612到变量?

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

谷歌很容易。无论如何,你可以使用下面的代码来完成它。

from bs4 import BeautifulSoup as bs

html='''<form class="addtoshoppingcart" name="addtoshoppingcart" action="/warenkorb/hinzugefuegen">
<input name="product_id" type="hidden" value="83612">
<input name="product_bs_id"  type="hidden" value="">
<input type="hidden" name="amount" type="text" value="1">
<div class="addToCartErrors"></div>
<button id="submitAddToCart" name="addToCart" class="button radius action" disabled='disabled' autocomplete="off">
  <span>In den Warenkorb</span>
</button>
</form>'''

soup=bs(html)

value = soup.find('input', {'name': 'product_id'}).get('value')
value = int(value) # if you want integer value