python - 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&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>
整个文件只是重复这个,几乎发现了不同的东西。
解决方案
调试 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 和集成调试器,但有时您只需要一个放置良好的打印语句。
推荐阅读
- eclipse - 保存文件时 Eclipse 上的异常行为
- jquery - 从数据库中选择第三级
- ngrx - 状态不应该是不可变的吗?
- python - ValueError:您正在尝试将包含 14 层的权重文件加载到具有 3 层的模型中
- opengl - GLSL 扩展在应该可用时不可用
- angular - 如何在角度 2 中的 @Component 中使用样式中的变量?如何在样式中使用名为 leftposition 的变量?
- nhibernate - NHibernate 和新创建的记录锁定
- javascript - Lodash 的“无”属性和输入数组
- angular - 在 Angular 中创建虚拟模型
- reactjs - 如何使用 jsdoc 记录 javascript 单元测试文件?