首页 > 解决方案 > 在python中从html获取2个值的最佳方法

问题描述

我正在使用 beautifulsoup,我想在 python 中抓取 2 个属性值。

<input type="hidden" name="test" value="123456789">
<input type="hidden" name="test" value="987654321">

我想同时获得这两个值。这是我现在正在使用的代码

number = BeautifulSoup(html, 'html.parser')
final = number.find('input')['name']
soup.find('input')['value']
print(final [2])

标签: pythonweb-scrapingbeautifulsoup

解决方案


你正在使用.find()它只给你第一个标签。您应该使用.find_all()来获取所有input标签,然后从中获取值。

from bs4 import BeautifulSoup

text = '''
<input type="hidden" name="test" value="123456789">
<input type="hidden" name="test" value="987654321">
'''

soup = BeautifulSoup(text, 'lxml')
values = [each.attrs['value'] for each in soup.find_all('input')]
# -> ['123456789', '987654321']

推荐阅读