2017-09-04 95 views
0

我想用python 2.7.13下载一个网页并逐行去分析它。从存储器和从周围搜索,我发现,下面的代码段将足以通过线走线:作为循环的语法错误

with s as f: 
    for line in f: 
     print line 

可变s由file.read(定义)和该文件由urllib2的开口限定指定的网址。不幸的是,当我运行该脚本,我得到这个语法错误:

Traceback (most recent call last): 
    File "a.py", line 12, in <module> 
    with s as f: 
AttributeError: __exit__ 

我老老实实目瞪口呆的我做错了什么,它会理解以获得有关我的错误见解。

+0

哪个版本的Python需要在'while'循环的条件'as'? –

+0

你从哪里得到这段代码? – birryree

+0

'as'关键字用于导入语句和例外。在这种情况下,您应该可以直接在文件对象中使用'for line in f:'来循环,不需要while循环。 – Aidan

回答

2

I found that the following code snippet would be sufficient to go line by line:

它,但对于文件对象

with open(filename) as f: 
    for line in f: 

The variable s is defined by a file.read()

这是一个字符串,而不能在with使用。

and the file is defined by urllib2 opening a specified url.

这是一个文件 - 对象,但恰好是迭代

I am trying to download a web page with python 2.7.13 and go line by line to analyze it.

任何有用的信息可以从迭代网站的线来收集。 (至少(X)HTML,JSON等)

尝试使用BeautifulSoup或XPath

+0

好的,我只记得我可以通过“\ n”和循环遍历列表来分割行。就像我说的,我今天非常雾。谢谢你的帮助。 – Yetoo

+0

您可以,但除非您的网站只包含多行文字,否则解析HTML更有意义 –