【发布时间】: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