|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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
不建议直接用索引,有时候会报错,我自己也没整清楚为啥,我用的是pop()这个方法
|
|