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

BS4:标记中的注释中断字符串属性和搜索功能[重复]

  •  0
  • robertspierre  · 技术社区  · 7 年前

    如果你打电话给 .string 在标记元素上,应返回标记中包含的文本。

    一串 属性突然返回 None .

    .text 尽管如此,属性似乎仍然有效,但是 find 据说它还在工作 text 属性不再工作。 那么如果没有评论的话,, 发现 发现

    这里是一个MWE:

    from bs4 import BeautifulSoup
    
    def test(html):
        soup = BeautifulSoup(html, 'lxml')
        tag = soup.find('span')
        print("TEXT {}: {}".format(type(tag.text), tag.text))
        print("STRING {}: {}".format(type(tag.string), tag.string))
        found = soup.find('span', text="Hello")
        print("Found: {}\n".format("Yes" if found != None else "No"))
    
    test('<span>Hello</span>')
    test('<span><!-- AA -->Hello</span>')
    

    以下是输出:

    TEXT <class 'str'>: Hello
    STRING <class 'bs4.element.NavigableString'>: Hello
    Found: Yes
    
    TEXT <class 'str'>: Hello
    STRING <class 'NoneType'>: None
    Found: No
    

    问题是:为什么会显示此行为,以及如何恢复 发现 功能?

    附笔。 find_all() 不为其中任何一个返回任何子项

    1 回复  |  直到 7 年前
        1
  •  0
  •   webh    7 年前

    如果标记只有一个子类型 NavigableString 那么只有 .string 会有用的。看见 https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string .

    BeautifulSoup - search by text inside a tag . 这对你的问题几乎没有解决办法。

    推荐文章