我今天正在研究 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/