繁体   English   中英

将BeautifulSoup内容写入文件

[英]Writing BeautifulSoup contents to a file

我最近问这个关于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()时,它似乎起作用。 我该如何解决?

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

错误的原因与写入文件没有任何关系。 似乎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")

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

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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM