求助:Python爬虫学术网址时,更换网址后,显示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)
num=input("请输入大致想获取的文章数目(总数为"+str(int(allpage[0].replace('\n ','').replace(',',''))*10)+"):")
allpage 时空的,新的网页里可能没有你要findall的数据
我觉得应该是你的正则匹配结果是空的
输出结果看看
allpage=re.compile(pat_allpage,re.S).findall(tdata)
print(allpage)
if len(allpage)>0:
num=input("请输入大致想获取的文章数目(总数为"+str(int(allpage[0].replace('\n ','').replace(',',''))*10)+"):")
新的网页你爬取的内容需要做调整。
debug 看一下是不是你要的数据,再做详细的数据处理
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使用正则表达式是一个列表,而列表是否有元素,不一定,由网页内容决定
1,判断列表的元素数量大于0,但是这种方法,如果返回元组的话,会引发其他的异常
if len(allpage) > 0:
print(allpage[0])
2,判断列表的元素不为空
if allpage != []:
print(allpage[0])
3,遍历列表的元素
for page in allpage:
if page != '':
print(page)