【问题标题】:best way to get 2 values from html in python在python中从html获取2个值的最佳方法
【发布时间】:2021-03-09 16:00:02
【问题描述】:

我正在使用 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])

【问题讨论】:

  • 您的实际问题是什么?如何找到这些元素?或者找到后如何提取值?
  • 我想找到它们并提取它们。现在我只能找到第一个。
  • 更新问题,向我们展示您迄今为止尝试过的代码。
  • .find(...) 返回第一个匹配项。你会想要.find_all(...) 和一个循环。

标签: python web-scraping beautifulsoup


【解决方案1】:

你正在使用.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']

【讨论】:

    猜你喜欢
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多