我最近在玩Beautifulsoup时遇到了一个奇怪的python字典问题。我的代码看起来像这样。dict.has_key(somekey)不能像dict中的somekey一样工作
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'表达式并未按照您的想法进行操作。你可能想要添加一些括号,现在在a)中它被读为'not((a.has_key('href')=='href'))。 – 2013-02-19 11:15:38