【问题标题】:Beautiful Soup 4 parse line美汤4解析线
【发布时间】:2020-11-23 04:06:15
【问题描述】:

我将如何使用 BS4 和 python3 解析以下行?我想提取“BH”和“Bahrain”。

<li><input class="checkboxSelect2" name="countries[]" type="checkbox" value="BH"/> Bahrain</li>

我可以得到“Bahrain”,但我不能得到“BH”

for l in allCountries.findAll("li"):
  print(l.value)
  print(l.text)

l.text 将返回 Bahrain 但 l.value 无效并引发错误。

【问题讨论】:

  • 请展示allCountries如何获得它的价值。

标签: python python-3.x beautifulsoup


【解决方案1】:

我想出了如何访问属性。我需要先做

l.input

然后我需要调用属性

l.input.attrs['value']

用于提取所有国家/地区名称和国家/地区缩写的最终代码

for l in allCountries.findAll("li"):
  try:
    print("Country: {0} ABR: {1}".format(l.text, l.input.attrs['value']))
  except:
    pass

【讨论】:

    猜你喜欢
    • 2011-04-20
    • 1970-01-01
    • 2017-09-29
    • 2018-05-08
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 2013-04-29
    相关资源
    最近更新 更多