鱼C论坛

 找回密码
 立即注册
查看: 3305|回复: 1

[作品展示] 萌新的爬虫——爬取斗罗小说

[复制链接]
发表于 2021-3-1 14:25:19 | 显示全部楼层 |阅读模式

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

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

x
直接上代码:
  1. import requests
  2. import time
  3. import re
  4. import os
  5. from bs4 import BeautifulSoup

  6. path = "D:/APython/spider/douluo/斗罗大陆3龙王传说/"# 路径记得改
  7. url = "https://www.bifeige.com/9_9235/"

  8. def openurl(url):
  9.     headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.81"}
  10.     respound = requests.get(url, headers=headers)
  11.     respound.encoding = respound.apparent_encoding
  12.     return respound.text

  13. def save_text(respound, name):
  14.     # 解析并保存文件
  15.     try:
  16.         soup = BeautifulSoup(respound, "html.parser")
  17.         targets = soup.find_all("div", id="content")
  18.         with open(path + name, "a", encoding="utf-8") as f:
  19.             for target in targets:
  20.                 f.write(target.text)
  21.                 print("下载成功;" + name)
  22.     except OSError:
  23.         return ""

  24. respound = openurl(url)
  25. soup = BeautifulSoup(respound, "html.parser")
  26. targets = soup.find_all("dd")
  27. i = 1

  28. for target in targets:
  29.     name = str(target.text)+ ".txt"
  30.     if not os.path.exists(path  + name):
  31.         url = "https://www.bifeige.com" + str(target.a.get("href"))
  32.         respound = openurl(url)
  33.         save_text(respound, name)
  34.         if i % 10 == 0:
  35.             time.sleep(10)
  36.         i += 1
复制代码

本帖被以下淘专辑推荐:

  • · python|主题: 62, 订阅: 4
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-5-10 05:56:40 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-5-19 18:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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