目录
前因
在写爬虫代码时候代码报错
indexerror: list index out of range
indexerror:列表索引超出范围
开始的认为原因
前一期的博客我准备爬取盗版小说的的小说时,因为加载的字数太多
我就想然后就是因为这个报了这个错误
源代码(总)
带上代码
import requests
import re
import numpy as np
from bs4 import BeautifulSoup
#目标url
url='http://www.ibiqu.org/148_148106/'
#主页网站,不加的话还要后面分离链接
url2='http://www.ibiqu.org'
#定义头文件
head_bqg={
'User-Agent':'Mozilla/5.0 (Linux; A
}
html_zhuye=requests.get(url,headers=head_bq
html_1=BeautifulSoup(html_zhuye.text,'html.
html_1.select('body > div.cover > ul > a >h
html_1=str(html_1)
ex='<dd><a href="(.*?)".*?'
ex=re.compile(ex)
imglists = re.findall(ex, html_1)
url_lists=np.array([])
for imglist in imglists:
url_max=f'{url2}{imglist}'
url_lists=np.append(url_lists,url_m
print(url_lists)
file_1= open('114514.txt','w')
for url_list in url_lists:
txt_novel=requests.get(url_list,hea
ex='<div id="content">(.*?)</div>'
re.compile(ex)
txt_2=re.findall(ex,txt_novel.text)
ex_1='<p>\u3000\u3000|</p>'
re.compile(ex_1)
txt_2=re.sub(ex_1,'',txt_2[0])
txt_2=str(txt_2)[2:-2]
file_1.writelines(f'{txt_2}\n')
真正原因
后来我想到那为什么还有其他的文字的python项目爬虫爬取的项目比我长了好几倍,但是它依然不会报错
不对劲,我感觉
后来我联系源码内容
想到是不是因为我的一些数据下标没有(也就是空数组),导致下面代码
txt_2=re.sub(ex_1,'',txt_2[0])
txt_2=str(txt_2)[2:-2]
根本找不到下标
解决办法
最后不图省事了,直接遍历列表,这样空的列表也就会跳过
for txt_3 in txt_2:
txt_3=re.sub(ex_1,'',txt_3)
file_1.writelines(f'{txt_3}\n')
结果十分奇怪,它不报错了,但是好像要加载很久,过一段时间再想一想这里还有没有优化的内容
实在不行就直接把需要爬取的链接存取到列表里然后运行一次程序爬取一行链接存储到文档中。
所以最后总代码
import requests
import re
import numpy as np
from bs4 import BeautifulSoup
#目标url
url='http://www.ibiqu.org/148_148106/'
#主页网站,不加的话还要后面分离链接
url2='http://www.ibiqu.org'
#定义头文件
head_bqg={
'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36 Edg/114.0.1823.37'
}
html_zhuye=requests.get(url,headers=head_bqg)
html_1=BeautifulSoup(html_zhuye.text,'html.parser')
html_1.select('body > div.cover > ul > a >href')
html_1=str(html_1)
ex='<dd><a href="(.*?)".*?'
ex=re.compile(ex)
imglists = re.findall(ex, html_1)
url_lists=np.array([])
for imglist in imglists:
url_max=f'{url2}{imglist}'
url_lists=np.append(url_lists,url_max)
print(url_lists)
file_1= open('114514.txt','w')
for url_list in url_lists:
txt_novel=requests.get(url_list,headers=head_bqg)
ex='<div id="content">(.*?)</div>'
re.compile(ex)
txt_2=re.findall(ex,txt_novel.text)
ex_1='<p>\u3000\u3000|</p>'
re.compile(ex_1)
for txt_3 in txt_2:
txt_3=re.sub(ex_1,'',txt_3)
file_1.writelines(f'{txt_3}\n')
# for txt_3 in txt_2:
# file_1.writelines(f'{txt_3}\n')
file_1.close()
问题总结
python列表为空的原因导致索引错误,继而导致找不到索引
个人总结
不要图省事,至少在报错的时候最好用最基础的方法试一遍