我最近問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