我正在尝试执行以下 python 代码
import httplib2
from BeautifulSoup import BeautifulSoup, SoupStrainer
http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')
for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
if link.has_attr('href'):
print link['href']
编辑: 我把代码改成了这个
for link in BeautifulSoup(response).find_all('a', href=True):
print link['href']
还是报错
我遇到了错误
Traceback (most recent call last):
File "/home/user1/Documents/machinelearning/extract_links.py", line 8, in <module>
if link.has_attr('href'):
TypeError: 'NoneType' object is not callable
这个错误的原因是什么? 我该如何解决这个问题?
请您参考如下方法:
您的列表返回了一堆值以及其中的 None。
在我看来,你最好在这里使用 find_all():
for link in BeautifulSoup(response).find_all('a', href=True):
print link['href']
href=True 只会找到具有 href 值的标签,因此您不需要条件。
