我想编写一个简单的代码,从网站内容创建一个html文件。我正在使用beautifulsoup 4
库。在创建BeautifulSoup
对象时:
BeautifulSoup('<html></html>')
我知道这个错误:
语法无效(init.py,第175行)
这一行产生了错误:
从bs4导入BeautifulSoup
我通过执行setup.py
安装了这个库。
有什么问题吗?
我的全部代码:
import urllib.request as req
from bs4 import BeautifulSoup
def main():
get_announcements("92-93", 1, 153, 12)
def get_announcements(year, term, courseID, group):
website = req.urlopen('http://ce.sharif.edu/courses/' + year + '/' + str(term) + '/ce' + str(courseID) + '-' + str(group) + '/')
site_content = website.readall()
soup = BeautifulSoup('<html></html>')
if __name__ == '__main__':
main()
以及库文件中的init.py中的错误行:
try:
is_file = os.path.exists(possible_filename)
except Exception, e: #ERROR!!
# This is almost certainly a problem involving
# characters not valid in filenames on this
# system. Just let it go.
pass
发布于 2013-11-25 02:08:45
你不会让这件事变得太容易,但我认为在你发布的文章中有足够的信息来解决你的问题。
import urllib.request as req
只有当您使用Python3.x时,这一行才能工作,因为您通过了这一行,我将假设情况就是这样。
except Exception, e:
这一行使用Python2.x语法。您似乎试图在Python3.x程序中导入Python2.x库。那不管用。在Python3中,except
子句具有以下语法(因此需要as
而不是逗号):
("except" [expression ["as" target]] ":" suite)+
为了验证,如果我的假设是正确的,语法错误应该是将逗号表示为产生问题的实际字符。
我不知道你为什么会这样。我刚刚使用bs4安装了pip install BeautifulSoup4
,而为我安装的版本中的代码是第175行:
try:
is_file = os.path.exists(possible_filename)
except Exception as e:
# This is almost certainly a problem involving
# characters not valid in filenames on this
# system. Just let it go.
pass
这样就行了。
发布于 2015-01-24 12:59:10
我能够在MacOSX10.10.1上重现这个问题,它与OSX一起发布了最初的Python2.7.6版本,在3.4.2版上实现了Python空闲版。使用后
python3 setup.py install
我也犯了同样的错误:
>>> import bs4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Applications/Python 3.4/beautifulsoup4-4.3.2/bs4/__init__.py", line 175
except Exception, e:
^
SyntaxError: invalid syntax
安装程序可能读取/Library/ Python / 2.7 /site-packages/的默认安装目录,并假设BeautifulSoup将在Python2.7上运行。看起来像是安装程序中的一个bug。
发布于 2015-04-28 08:31:48
解决方案可以找到这里。
问题是您下载的模块是用python版本2编写的,它的语法与您在计算机上安装的python版本(版本3)不兼容。
要解决这个问题,请使用位于...\Python34\Tools\Scripts
中的...\Python34\Tools\Scripts
工具手动将bs4目录(...\beautifulsoup4-4.3.2\bs4)
中的每个python文件从版本2转换为版本3。
例如,键入
'C:\Python34\Tools\Scripts\2to3.py ...\beautifulsoup4-4.3.2\bs4\__init__.py'
在命令提示符中,__init__.py
文件将从版本2转换为版本3。
https://stackoverflow.com/questions/20174305
复制相似问题