鱼C论坛

 找回密码
 立即注册
查看: 2160|回复: 2

[已解决]求助IndexError

[复制链接]
发表于 2017-3-28 20:05:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 秋名86 于 2017-3-28 20:15 编辑


win7 64bit
python 3.5.3

想要抓取新闻标题

代码及错误如下:

#导入Beautifulsoup

import requests
from bs4 import BeautifulSoup

#创建结果的空字典

result       = {}

#以get方法取得response内容

newsurl = input('网址')
res          = requests.get(newsurl)

#导入解析器

res.encoding = 'utf-8'
soup         = BeautifulSoup(res.text,'html.parser')

#用select方法筛选id为artibodytitle的内容到列表,选取索引为0的元素并取得文本部分。

result['title']      = soup.select('#artibodytitle')[0].text


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-34-69cd744f964c> in <module>()
     12 soup         = BeautifulSoup(res.text,'html.parser')
     13
---> 14 result['title']      = soup.select('#artibodytitle')[0].text
     15 '''result['newssource'] = soup.select('.time-source span a')[0].text
     16     timesource           = soup.select('.time-source')[0].contents[0].strip()

IndexError: list index out of range
最佳答案
2017-3-30 17:28:02
不建议直接用索引,有时候会报错,我自己也没整清楚为啥,我用的是pop()这个方法
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-3-30 17:28:02 | 显示全部楼层    本楼为最佳答案   
不建议直接用索引,有时候会报错,我自己也没整清楚为啥,我用的是pop()这个方法
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-4-2 00:39:29 | 显示全部楼层
artibodyTitle我写错了,应该是大写。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 17:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表