2014-02-25 43 views
0

所以使用Python 2.7,现在从3.3.4无效的语法字符串比较蟒蛇维基解析器

恢复回后,我使用

import sys 
import urllib 
import urllib2 
from bs4 import BeautifulSoup 

article = sys.argv[1] 
articleURL = urllib.quote(article) 
print article 
opener = urllib2.build_opener() 
opener.addheaders = [('User-agent', 'Mozilla/5.0')] 

MAX_HOPS = 100 
count=1 

While article!="Philosophy" and count<MAX_HOPS: 
    resource = opener.open("http://en.wikipedia.org/wiki/" + articleURL) 
    data = resource.read() 
    resource.close() 
    soup = BeautifulSoup(data) 
    print soup.find('div',id="bodyContent").p 
    count+=1 

的同时文章!=“哲学”我得到一个无效语法指向文章的错误。任何想法我做错了

+0

'while'!='while'。后者是一个Python循环命令。前者是未定义的,因此语法错误... – ig0774

回答

0

它是while,而不是While(即小写w)。解释者认为While是一个名称,它试图解析一个赋值或表达式,并且它在article处失败。

1

如果您的代码段是你执行的确切的代码,它会产生以下异常:

File "<stdin>", line 1 
    While article!="Philosophy" and count<MAX_HOPS: 
       ^
SyntaxError: invalid syntax 

的问题是资本W在线路While article!="Philosophy" and count<MAX_HOPS:即使回溯指向的文章。

解决方案很简单。使用while而不是While

关于Python SyntaxError s,有时回溯并不完美。如果输出有点混乱,请在显示的行/部分之前查看一下。