Python爬虫出现list index out of range

近日,使用爬虫提取xpath列表时,空列表报错list index out of range。

import requests
import re
key=input("请输入你想查找的信息:")
local_url=input("请输入你想存储的位置及名称:")
turl="https://cn.bing.com/academic/"
tdata=requests.get(turl,params={"term":key}).text
pat_allpage='(.*?)'
allpage=re.compile(pat_allpage,re.S).findall(tdata)


if allpage != []:
    num=input("请输入大致想获取的文章数目(总数为"+str(int(allpage[0].replace('\n ','').replace(',',''))*10)+"):")
# 首先allpage使用正则表达式是一个列表,而列表是否有元素,不一定,由网页内容决定。

# 判断列表的元素数量大于0,但是这种方法,如果返回元组的话,会引发其他的异常
if len(allpage) > 0:
    print(allpage[0])

# 判断列表的元素不为空
if allpage != []:
    print(allpage[0])

# 遍历列表的元素
for page in allpage:
    if page != '':
        print(page)

参考链接:
https://ask.csdn.net/questions/1094581

本文链接:

https://ma.ge/archives/506.html
1 + 7 =
快来做第一个评论的人吧~