如何从String访问整数索引?

时间:2014-03-03 05:50:58

标签: python python-3.x beautifulsoup ipython-notebook

我正在尝试提取标题;来自网页的标题,但我只得到一个元素。

from BeautifulSoup import BeautifulSoup

import urllib2 
url = urllib2.urlopen("http://timesofindia.indiatimes.com/")

content = url.read()
patFinderTitle = re.compile('')
listIterator = []

listIterator[:] = range(2,16)

soup2 = BeautifulSoup(content)

soup2.findAll("title")
print soup2.findAll("h1")




for i in soup2.findAll("title"):
  print titleSoup[i]

  print "\n"

我在for循环中收到错误,即

TypeError: list indices must be integers, not Declaration

1 个答案:

答案 0 :(得分:1)

如果您要打印所有title标记,只需打印i即可。 (i不是索引。在迭代title结果时,每个i元素都分配给findAll

for i in soup2.findAll("title"):
    print i
    print "\n"