【问题标题】:how to select specific values of an element in python3如何在python3中选择元素的特定值
【发布时间】:2020-07-06 03:47:06
【问题描述】:

这是我的第一个问题,所以它可能非常基本。 我已经设法识别并选择了元素,但我无法从中提取特定值,例如“IDinmobiliarias”。

data = soup.select('#PropJSON')
print(data)

当我这样做时,我得到这个输出:

[<input id="PropJSON" type="hidden" value='{"id":"186226916","IDinmobiliarias":"108","IDoperaciones":"1","tipoPropiedad":"2","IDdepartamentos":"10","IDzonas":"13","IDpais":"1","refered":1,"particular":"0","temporario":0,"proyecto":0,"destaque":1,"IDmoneda":"1","monto":"1595000","precio_en_usd":1595000,"monedaISO":"USD"}'/>]

例如,如何提取“108”? 我尝试了不同的方法但没有成功。

【问题讨论】:

    标签: python-3.x css-selectors distinct-values


    【解决方案1】:

    select 会返回给你一个列表。然后,您可以遍历该列表并通过像字典一样访问它来获取 value 属性的数据。获得数据后,您需要使用 json 对其进行解析,然后您可以从中选择任何您喜欢的元素。

    from bs4 import BeautifulSoup
    import json
    html = """<input id="PropJSON" type="hidden" value='{"id":"186226916","IDinmobiliarias":"108","IDoperaciones":"1","tipoPropiedad":"2","IDdepartamentos":"10","IDzonas":"13","IDpais":"1","refered":1,"particular":"0","temporario":0,"proyecto":0,"destaque":1,"IDmoneda":"1","monto":"1595000","precio_en_usd":1595000,"monedaISO":"USD"}'/>"""
    soup = BeautifulSoup(html, features="lxml")
    data = soup.select('#PropJSON')
    for input_tag in data:
        json_string = json.loads(input_tag['value'])
        print(json_string['IDinmobiliarias'])
    

    输出

    108
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      相关资源
      最近更新 更多