TypeError:在 Python 中使用 split 和 BeautifulSoup 时,“NoneType”对象不可调用

2024-01-06

我今天正在研究 BeautifulSoup 和 Requests API。所以我想我应该写一个简单的抓取工具,它会跟踪深度为 2 的链接(如果这有意义的话)。我正在抓取的网页中的所有链接都是相对的。 (例如:<a href="/free-man-aman-sethi/books/9788184001341.htm" title="A Free Man">)所以为了使它们绝对,我想我会使用相对链接将页面网址加入urljoin.

为此,我必须首先从<a>标签,为此我想我会使用split:

#!/bin/python
#crawl.py
import requests
from bs4 import BeautifulSoup
from urlparse import urljoin

html_source=requests.get("http://www.flipkart.com/books")
soup=BeautifulSoup(html_source.content)
links=soup.find_all("a")
temp=links[0].split('"')

这会产生以下错误:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    temp=links[0].split('"')
TypeError: 'NoneType' object is not callable

在正确阅读文档之前,我意识到这可能不是实现我的目标的最佳方法,但为什么会出现类型错误?


links[0]不是一个字符串,它是一个bs4.element.Tag。当你尝试抬头时split在其中,它发挥了它的魔力,并尝试找到一个名为的子元素split,但没有。你称其为“无”。

In [10]: l = links[0]

In [11]: type(l)
Out[11]: bs4.element.Tag

In [17]: print l.split
None

In [18]: None()   # :)

TypeError: 'NoneType' object is not callable

使用索引来查找 HTML 属性:

In [21]: links[0]['href']
Out[21]: '/?ref=1591d2c3-5613-4592-a245-ca34cbd29008&_pop=brdcrumb'

Or get如果存在不存在属性的危险:

In [24]: links[0].get('href')
Out[24]: '/?ref=1591d2c3-5613-4592-a245-ca34cbd29008&_pop=brdcrumb'


In [26]: print links[0].get('wharrgarbl')
None

In [27]: print links[0]['wharrgarbl']

KeyError: 'wharrgarbl'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeError:在 Python 中使用 split 和 BeautifulSoup 时,“NoneType”对象不可调用 的相关文章

随机推荐