2013-01-19 94 views
0

我最近问this关于在BeautifulSoup中编码印地文字符的问题。 该问题的答案确实解决了这个问题,但是我有另一个问题。将BeautifulSoup内容写入文件

我的代码是:

import urllib2 
from bs4 import BeautifulSoup 

htmlUrl = "http://archives.ndtv.com/articles/2012-01.html" 
FileName = "NDTV_2012_01.txt" 

fptr = open(FileName, "w") 
fptr.seek(0) 

page = urllib2.urlopen(htmlUrl) 
soup = BeautifulSoup(page, from_encoding="UTF-8") 

li = soup.findAll('li') 
for link_tag in li: 
    hypref = link_tag.find('a').contents[0] 
    strhyp = hypref.encode('utf-8') 
    fptr.write(strhyp) 
    fptr.write("\n") 

我得到一个错误

Traceback (most recent call last): 
File "./ScrapeTemplate.py", line 29, in <module> 
hypref = link_tag.find('a').contents[0] 
IndexError: list index out of range 

看来,当我替补print strhyp而不是fptr.write()工作。我该如何解决?

编辑:代码有一个错误,我没有发现。修正了它,但我仍然得到相同的错误。

+0

我试过你的代码,我没有得到任何错误。你想达到什么目的?想要获得链接的href吗?你能发布你的预期输出吗?谢谢。 –

+0

@AnneLagang - 更改了代码。输出应该是HTML页面中的标题列表,除了我收到此错误。 – Kitchi

回答

1

您的代码正在跳过页面底部的链接。跳过这些:

for link_tag in li: 
    contents = link_tag.find('a').contents 
    if len(contents) > 0: 
    hypref = contents[0] 
    strhyp = hypref.encode('utf-8') 
    fptr.write(strhyp) 
    fptr.write("\n") 
+0

哦,对!我没有检查终端的整个方式。这很有用,谢谢! – Kitchi

1

错误的原因与写入文件没有任何关系。看起来link_tag.find('a').contents有时会返回一个空列表,并在尝试获取第一个项目时出现错误。您可以尝试如下所示:

for link_tag in li: 
    try: 
     hypref = link_tag.find('a').contents[0] 
    except IndexError: 
     print link_tag #print link tag where it couldn't extract the 'a' 
     continue 
    strhyp = hypref.encode('utf-8') 
    fptr.write(strhyp) 
    fptr.write("\n") 
+0

但是,当我将相同的代码直接打印到终端时,不会出现错误,这就是为什么我怀疑问题在于写入文件。 – Kitchi

+0

@Kitchi它也发生如果你打印到终端(我试过)。你的代码跳过页面底部的链接(RSS,新闻快讯,手机等) – oefe