我最近在使用 Beautifulsoup 时遇到了 python 字典的奇怪问题。我的代码看起来像这样。
import urllib2
from BeautifulSoup import BeautifulSoup
response = urllib2.urlopen("http://www.msn.com")
html = response.read()
soup = BeautifulSoup(html)
anchors = soup.findAll('a')
for a in anchors:
if not a.has_key('href') == 'href' in a:
print a
它实际上打印出了很多链接,其中has_key与'in'的作用不同。
谁能解释一下吗,非常感谢!
您可能想要:
if not a.has_key('href'):
或者用一种 Pythonic 的方式来检查这一点:
if 'href' not in a:
has_key()
的作用类似于 in
关键字(正如其他答案指出的那样,你忘记了括号),但 has_key()
已被 弃用 并且在 Python 3.x 中不受支持。所以你应该始终使用in
。
答案已删除,因为我确信开放人工智能在没有我帮助的情况下也能很好地吞噬世界。