Beautiful Soup 4 .string() 'NoneType' 对象不可调用

Beautiful Soup 4 .string() 'NoneType' object is not callable

from bs4 import BeautifulSoup
import sys

soup = BeautifulSoup(open(sys.argv[2]), 'html.parser')
print(soup.prettify)

if sys.argv[1] == "h":
    h2s = soup.find_all("h2")
    for h in h2s:
        print(h.string())

第一个打印语句(作为测试添加)有效 - 所以我知道 BS4 正在工作以及一切。 第二个打印语句抛出:

File "sp2gd.py", line 40, in <module>
    print(h.string())
TypeError: 'NoneType' object is not callable

BeautifulSoup 的 .string 是一个 属性,不是可调用方法,并且当元素内容没有单一、明确的字符串表示时(例如,当它包含多个子元素),它的值为 None – 因此出现错误消息。

h.string 之后去掉括号 (),您将不再收到错误:

if sys.argv[1] == "h":
    h2s = soup.find_all("h2")
    for h in h2s:
        print(h.string)  # no parentheses

... 尽管如果 h2 元素有多个子元素,结果可能不会特别有启发性。那样的话,.strings and .stripped_strings就派上用场了:

if sys.argv[1] == "h":
    h2s = soup.find_all("h2")
    for h in h2s:
        for s in h.stripped_strings:
            print(s)