【问题标题】:Writing BeautifulSoup contents to a file将 BeautifulSoup 内容写入文件
【发布时间】:2013-01-19 10:19:11
【问题描述】:

我最近向this 询问了有关在 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() 时,它似乎有效。我该如何解决这个问题?

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

【问题讨论】:

  • 我试过你的代码,我没有收到任何错误。你想达到什么目的?想获取链接的href吗?你能发布你的预期输出吗?谢谢。
  • @AnneLagang - 更改了代码。输出应该是 HTML 页面中的标题列表,但我收到此错误。

标签: python web-scraping beautifulsoup


【解决方案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")

【讨论】:

  • 哦,对了!我没有在终端检查整个过程。这非常有效,谢谢!
【解决方案2】:

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

【讨论】:

  • 但是当我将相同的代码直接打印到终端时没有出现错误,这就是为什么我怀疑问题出在写入文件。
  • @Kitchi 如果您打印到终端也会发生这种情况(我试过了)。您的代码绊倒了页面底部的链接(RSS、新闻快讯、移动设备等)
猜你喜欢
  • 2016-09-28
  • 2012-05-18
  • 1970-01-01
  • 2013-08-01
  • 2010-11-09
  • 2018-01-08
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多