首页 > 解决方案 > Python NoneType' 对象不是来自(我认为)str.split 函数的可调用错误

问题描述

我试图通过搜索以开头的所有行td然后拆分字符串以仅使用以下代码获取我想要的行的位来从 html 文件中获取信息:

def scraper(filename):
    soup = BeautifulSoup(open(filename), 'html.parser')
    with open("test/"+filename.stem+".txt", "w") as outfile:
        search = soup.findAll('td')
        for tag in search:
            if re.search(r'regbutton|rgba|mibig', str(tag)):
                if re.search('regbutton', str(tag)):
                    outfile.write(str(tag.split()[2]) + '\n')
                if re.search('rgba', str(tag)):
                    outfile.write(str(tag.split()[17]) + '\n')
                if re.search('mibig', str(tag)):
                    outfile.write(str(re.findall('>(.+)<')) + '\n')

但这会导致此错误:

Traceback (most recent call last):
  File "html_scrape.py", line 31, in <module>
    scraper(filename)
  File "html_scrape.py", line 23, in scraper
    outfile.write(str(tag.split()[2]) + '\n')
TypeError: 'NoneType' object is not callable
(antismash_v5) [lamma@fe1 actinobacteria]$

我明白这是因为我假设某些东西tag.split没有,但我不知道为什么。

编辑:

td标签搜索输出示例:

<td class="regbutton NRPS r2c1">
<a href="#r2c1">Region&amp;nbsp2.1</a>
</td>
<td><a class="external-link" href="https://mibig.secondarymetabolites.org/go/BGC0000324/1" target="_blank">coelibactin</a></td>
<td class="digits similarity-text" style="background-image: linear-gradient(to left, rgba(0, 100, 0, 0.3), rgba(0, 100, 0, 0.3) 100%, #ffffff00 100%)">100%</td>

整个文件只是重复这个,几乎发现了不同的东西。

标签: pythonsplit

解决方案


调试 101:简化您的问题并为自己提供更多信息。

您的问题与 tag.split() 有关。因此,让我们忽略 file.write 和其他所有内容:

def scraper(filename):
    soup = BeautifulSoup(open(filename), 'html.parser')
    search = soup.findAll('td')
    for tag in search:
        print(tag)
        print(tag.split())
        print(tag.split()[2])

    #with open("test/"+filename.stem+".txt", "w") as outfile:
    #    search = soup.findAll('td')
    #    for tag in search:
    #        if re.search(r'regbutton|rgba|mibig', str(tag)):
    #            if re.search('regbutton', str(tag)):
    #                outfile.write(str(tag.split()[2]) + '\n')
    #            if re.search('rgba', str(tag)):
    #                outfile.write(str(tag.split()[17]) + '\n')
    #            if re.search('mibig', str(tag)):
    #                outfile.write(str(re.findall('>(.+)<')) + '\n')

看看你的输出。拆分是否按您期望的方式工作?

额外的问题:如果 split 是一个内置的字符串函数,你为什么要用该str函数将所有内容都转换为字符串?

专业提示:使用 REPL 并以交互方式运行这些命令。使用内省来找出正在发生的事情。您可以使用 IDE 和集成调试器,但有时您只需要一个放置良好的打印语句。


推荐阅读