鱼C论坛

 找回密码
 立即注册
查看: 2202|回复: 2

python爬虫爬取小说下载问题

[复制链接]
发表于 2020-3-19 18:42:05 | 显示全部楼层 |阅读模式

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

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

x
  1. import requests
  2. import re
  3. import bs4
  4. '''
  5. 1.获取页面源代码
  6. 2.获取章节链接
  7. 3.获取章节页面源码
  8. 4.获取章节内容
  9. 5下载
  10. '''


  11. def get_url():
  12.     url = 'https://www.dukeba.com/947/'
  13.     headers ={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'}
  14.     res = requests.get(url,headers =headers)
  15.     res.encoding='gbk'

  16.     soup =bs4.BeautifulSoup(res.text,'html.parser')
  17.     data=[]
  18.     for dd in soup.find_all('dd'):
  19.         link = dd.find('a')
  20.         if not link:
  21.             continue
  22.         data.append(('https://www.dukeba.com/947/%s'%link['href'],link.get_text()))
  23.     return data


  24. def content(res):
  25.     headers ={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'}
  26.     r = requests.get(res,headers =headers)
  27.     r.encoding='gbk'

  28.     '''
  29.     soup =bs4.BeautifulSoup(r.text,'html.parser')
  30.     soup2= soup.find('div',id='content').get_text()
  31.     soup2.replace('/xa0','')
  32.     return soup2'''
  33.     reg='<div id="content">(.*?)</div>'
  34.     chapt_content =re.findall(reg,r.text,re.S)
  35.     #数据清洗未成功
  36.     chapt_content =chapt_content[0].replace('&nbsp;','')
  37.     chapt_content =chapt_content.replace('<br />','')
  38.     return chapt_content

  39. def main():
  40.     for data in get_url():
  41.         res,title = data
  42.         print("正在下载%s"%title)
  43.         with open(r'C:\Users\liuhang\Desktop\os创建文件夹\%s.txt'%title,'w') as file:
  44.             file.write(content(res))
  45.         

  46. main()
复制代码

如题,为什么只能下载保存两章小说,然后会报错
IndexError: list index out of range
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-3-19 19:00:38 From FishC Mobile | 显示全部楼层
这错误多明显啊,list索引超范围了
比如,list有两个值,你非要取第三个,你让他咋取
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-24 11:22:51 | 显示全部楼层
列表索引超出范围了,再检查一下你的代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-8 21:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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