TypeError:在使用带有BeautifulSoup的Python中拆分时,'NoneType'对象不可调用

Cha*_*tem 2 python beautifulsoup python-requests

我今天正在玩BeautifulSoup和Requests API.所以我想我会写一个简单的刮刀,它会跟随深度为2的链接(如果这是有道理的).我正在抓取的网页中的所有链接都是相对的.(例如:)<a href="/free-man-aman-sethi/books/9788184001341.htm" title="A Free Man">所以为了使它们绝对我认为我会加入页面url与相关链接使用urljoin.

要做到这一点,我必须首先从<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('"')
Run Code Online (Sandbox Code Playgroud)

这会出现以下错误:

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

在正确浏览文档之前潜入水中,我意识到这可能不是实现我的目标的最佳方法,但为什么会出现TypeError?

Pav*_*sov 5

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
Run Code Online (Sandbox Code Playgroud)

使用索引查找HTML属性:

In [21]: links[0]['href']
Out[21]: '/?ref=1591d2c3-5613-4592-a245-ca34cbd29008&_pop=brdcrumb'
Run Code Online (Sandbox Code Playgroud)

或者,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'
Run Code Online (Sandbox Code Playgroud)