繁体   English   中英

在Python3中替换方法has_key

[英]Replacement of Method has_key in Python3

我想改变这个

def has_class_but_no_id(tag):
    return tag.has_key('class') and not tag.has_key('id')

此功能来自Python2,不适用于Python3

我知道

我在这样的列表中更改了此HTML文档

list_of_descendants = list(soup.descendants)

所以我可以获取包含类但没有id的标签,这是关于找到所有带有class = blabla...而不是id = ....标签class = blabla...我不知道如何处理此问题

文件说:

我重命名了一种与Python 3兼容的方法:

  • Tag.has_key() -> Tag.has_attr()

此外, 此处文档提供了完全相同的功能:

如果没有其他匹配项对您有用,则定义一个将元素作为唯一参数的函数。 如果参数匹配,则函数应返回True ,否则返回False

如果标签定义了“ class”属性但未定义“ id”属性,则此函数返回True

 def has_class_but_no_id(tag): return tag.has_attr('class') and not tag.has_attr('id') 

嘿,我解决了这个问题。

我要做的是

1.收集所有标签(BeautifulSoup)和所有标签子(内容)

soup = BeautifulSoup(html_doc,"html.parser")
list_of_descendants = list(soup.descendants)

2.消除所有NavigableStrings(因为它们不能接受has_attr()方法)

def terminate_navis(list_of_some):

    new_list = []

    for elem in list_of_some:

        if type(elem) == bs4.element.Tag:
            new_list.append(elem)
        else :
            continue

    return new_list 


new_list = terminate_navis(list_of_descendants)


def contents_adding(arg_list):
//this Method helps that get all the childrens of tags in lists again

    new_list = arg_list

    child_list = []

    for elem in arg_list:

        if elem.contents:

            child_list = elem.contents
            child_list = terminate_navis(child_list)
            new_list.extend(child_list)

        new_list = list(set(new_list))

    return new_list

3.如果所有标签都具有属性'class'(has_attr)和没有'id'(也具有has_attr),请对其进行过滤

def justcl(tag_lists):

    class_lists = []

    for elem in tag_lists:
        if elem.has_attr('class'):
            class_lists.append(elem)
        else :
            continue

    return class_lists

def notids(class_lists):

    no_id_lists = []

    for elem in class_lists:

        if elem.has_attr('id'):
            continue
        else :
            no_id_lists.append(elem)

    return no_id_lists
  1. 所有这些收集的标签将创建为列表并在屏幕上打印

打印或使用for循环等...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM