鱼C论坛

 找回密码
 立即注册
查看: 1153|回复: 3

一个列表推导式的错误(代码内含爬虫)

[复制链接]
发表于 2021-8-17 15:39:50 | 显示全部楼层 |阅读模式

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

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

x
代码:
from bs4 import BeautifulSoup
import requests as re
headers={}
headers["User-Agent"]="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.73"
web = None
soup = None
page_url = ["https://movie.douban.com/top250"]
def fulsh(url_name=''):
    global web,soup
    web = re.get(url_name,headers=headers)
    soup = BeautifulSoup(web.text,"html.parser")
def find():
    a=soup.find_all("div",class_="hd")
    name=[x.a.span.text for x in [x for x in a]]
    b = soup.find_all("div",class_="bd")
    writer = [x.p.text.strip()\
              .replace("\n",'').replace("\t",'').replace(" ",'').replace("\xa0",'')\
              for x in [x for x in b]][1:]
    c = soup.find_all("p",class_="quote")
    world = [x.span.text for x in [x for x in c]]
    b = (name,writer,world)
    return [(name[x]+' ',writer[x]+' ',world[x]) for x in range(len(name))]
    #return [(b[0][x]+' ',b[1][x]+' ',b[2][x]+' ') for x in range(len(b[0]))]


def main():
    global page_url
    return_=[]
    fulsh(page_url[0])
    page_url.extend([''.join(["https://movie.douban.com/top250",x.attrs['href']]) for x in soup.find_all("div",class_="paginator")[0].find_all("a")])
    for i in page_url:
        fulsh(i)
        return_.extend(find())
    retrun_='\n'.join(return_)
    return return_
if __name__ == '__main__':
    main()
报错代码:
Traceback (most recent call last):
  File "C:/Users/中维电器维修/Desktop/top250.py", line 37, in <module>
    main()
  File "C:/Users/中维电器维修/Desktop/top250.py", line 33, in main
    return_.extend(find())
  File "C:/Users/中维电器维修/Desktop/top250.py", line 22, in find
    return [(name[x]+' ',writer[x]+' ',world[x]) for x in range(1,23)]
  File "C:/Users/中维电器维修/Desktop/top250.py", line 22, in <listcomp>
    return [(name[x]+' ',writer[x]+' ',world[x]) for x in range(1,23)]
IndexError: list index out of range
本人python版本是3.8和3.9
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-8-17 15:56:47 | 显示全部楼层
列表超出索引了。
 return [(name[x]+' ',writer[x]+' ',world[x]) for x in range(len(name))]
索引用的全部是x?  是否长度会不一样?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-8-17 16:18:32 | 显示全部楼层
最基本的排错方法,发现哪个列表索引超出范围
就在生成该列表之后,使用该列表之前  print一下,看看是否是空列表  或者真的超索引了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-8-17 16:29:18 | 显示全部楼层
wp231957 发表于 2021-8-17 16:18
最基本的排错方法,发现哪个列表索引超出范围
就在生成该列表之后,使用该列表之前  print一下,看看是否 ...

不是,列表没问题,都是25,我自己导出来之后就没问题,但在函数里执行就有问题,不信你自己试试
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-10-8 02:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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