如何解决列表索引超范围错误Python?

2024-03-29 04:47:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习使用python进行web抓取。在

这是我的第一个python代码

# encoding=utf8
import urllib2
from bs4 import BeautifulSoup


soup = BeautifulSoup(urllib2.urlopen("http://www.bcsfootball.org/").read(),"lxml")

for row in soup("table", {'class': "mod-data"})[0].tbody("tr"):
    tds = row('td')
    print tds[0].string, tds[1].string

我弄错了

^{pr2}$

有谁能帮我做错事吗?在

还有一件事我想问…请帮我弄清楚这里到底发生了什么。。。在

for row in soup("table", {'class': "mod-data"})[0].tbody("tr"):

谢谢!!:)


Tags: inimportmodfordatastringtableurllib2
2条回答

错误消息意味着soup("table", {'class': "mod-data"})是一个空列表,但您希望获得该列表中的第一个元素。在

您应该确保table元素有一个使用类"mod-data"的节点。在

这样可以得到预期的结果:

import urllib2
from bs4 import BeautifulSoup


soup = BeautifulSoup(urllib2.urlopen("http://www.bcsfootball.org").read(),"html")

welcome = soup("div", {'class': "col-full"})[1] # we know it's index 1


for item in welcome:
   print item.string

相关问题 更多 >