【问题标题】:How to access integer index from String?如何从字符串访问整数索引?
【发布时间】:2014-03-03 05:50:58
【问题描述】:

我正在尝试从网页中提取标题和标题,但我只得到一个元素。

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

【问题讨论】:

  • titleSoup 是在哪里定义的?

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


【解决方案1】:

如果要打印所有title 标签,只需打印i。 (i 不是索引。每个title 元素在迭代findAll 结果时被分配给i):

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

【讨论】:

  • 谢谢,但它只打印一个标题,我想要页面中的整个标题
  • @Prashant,只有一个title 标签。
  • @Prashant,如果你指的是文章标题,你最好找到h1h2标签。
  • 其实我想访问网页的所有标题
  • 假设我想访问报纸的头条新闻。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-07
  • 2019-05-28
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
相关资源
最近更新 更多