python - 类型错误 : 'NoneType' object not callable when using split in Python with BeautifulSoup

标签 python beautifulsoup python-requests

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

为此,我必须首先从 <a> 中提取 href 值标签,为此我想我会使用 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

在正确阅读文档之前深入研究,我意识到这可能不是实现我的目标的最佳方法,但为什么会出现 TypeError?

最佳答案

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'

或者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'

关于python - 类型错误 : 'NoneType' object not callable when using split in Python with BeautifulSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15409132/

相关文章:

python - 从 Youtube 视频中抓取元素

python - 获取域中所有页面的所有内部链接

python - 无法在获取请求中使用 json 参数获得所需的响应

python - ValueError : matmul: Input operand 1 has a mismatch in its core dimension 0,,带有 gufunc 签名 (n?,k),(k,m?)->(n?,m?)(大小 1 与 3 不同)

python - 值错误 : zero length field name in format python

python - 如果测试失败,则停止/失败 docker build

python - 无法使用发布请求进入下一页

python - dynamodb boto put_item 类型为 Map "M"

python - 检查 BeautifulSoup 3 中的元素类型

python-2.7 - Python 电子邮件模块 ImportError : No module named utils