我最近问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()
工作。我该如何解决?
编辑:代码有一个错误,我没有发现。修正了它,但我仍然得到相同的错误。
我试过你的代码,我没有得到任何错误。你想达到什么目的?想要获得链接的href吗?你能发布你的预期输出吗?谢谢。 –
@AnneLagang - 更改了代码。输出应该是HTML页面中的标题列表,除了我收到此错误。 – Kitchi