代码之家  ›  专栏  ›  技术社区  ›  Hrvoje

漂亮的汤匹配HTML对象中的标记内容到变量

  •  -1
  • Hrvoje  · 技术社区  · 6 年前

    我有 soup 对象

    apt_object = soup.find(string="Data about object:").find_next('ul')
    

    它给出了以下信息 html :

    <ul>
    <li>New building</li>
    <li>Lift</li>
    <li>City pluming</li>
    <li>City sanitary</li>
    </ul>
    

    对于不同的页面,这将给出带有在中定义的预定义值的列表。 li 标签。

    我不想把所有的值都与预先定义的变量匹配,比如 ads_object_newBuilding 并将“是”分配给变量if <li>New building</li> 存在于HTML对象中,如果不存在则为“否”。

    到目前为止,我有一个解决方案列出了 标签 HTML 对象和检查是且不是执行分配:

    for li in apt_object:
        if li.string.strip().find("New building"):
            ads_object_newBuilding= "Yes"
        else: ads_object_newBuilding= "No"
        if li.string.strip().find("Lift"):
            apt_object_lift = "Yes"
        else: apt_object_lift = "No"
    

    我想知道变量的检查和赋值是否可以在一行中完成。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Rakesh    6 年前

    这是一种方法。

    前任:

    apt_object = soup.find(string="Data about object:").find_next('ul').text
    apt_objekt_novogradnja, apt_objekt_lift  = "No", "No"
    
    if "New building" in apt_object:
        apt_objekt_novogradnja = "Yes"
    if "Lift" in apt_object:
        apt_objekt_lift = "Yes"
    
    print(apt_objekt_novogradnja, apt_objekt_lift)
    
        2
  •  1
  •   bruno desthuilliers    6 年前

    您可以使用三元运算符:

    ads_object_newBuilding = "Yes" if li.string.strip().find("New building") else "No"