鱼C论坛

 找回密码
 立即注册
查看: 1491|回复: 0

爬取论坛 xx 版块的帖子的标题和链接

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

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

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

x
本帖最后由 一个账号 于 2020-3-30 18:37 编辑
  1. import requests
  2. import bs4
  3. import re
  4. import sys
  5. import threading
  6. import time

  7. from easygui import exceptionbox


  8. # 返回最后一页
  9. def return_last(res, method=1):
  10.     try:
  11.         soup = bs4.BeautifulSoup(res.text, "html.parser")
  12.         
  13.         if method == 1:
  14.             try:
  15.                 content = soup.find("a", class_="last")
  16.                 p = re.compile(r"\d")
  17.                 result = p.findall(content.text)
  18.                 num = int("".join(result))

  19.                 return num
  20.             
  21.             except AttributeError:
  22.                 return return_last(res, 2)
  23.       
  24.         else:
  25.             content = soup.find("div", class_="pg")
  26.             num = content.text.find("/")
  27.             p = re.compile(r"\d")
  28.             result = p.findall(content.text[num:])
  29.             num = int("".join(result))
  30.             
  31.             return num
  32.     except:
  33.         return False


  34. # 写入内容并保存
  35. def write(content, num=1, end=False, url=""):   
  36.     file = open("帖子.txt", "a", encoding="utf-8")
  37.     prefix = ""

  38.     # 读取每一行并写入
  39.     for each in content:
  40.         file.write(str(num) + ". " + each.text + "  ————>  " + prefix + each["href"] + "\n\n")
  41.         num += 1

  42.     if not end:
  43.         file.write("-" * 110 + "\n\n")

  44.     file.close()

  45.     return num


  46. # 寻找帖子
  47. def find_data(res):
  48.     soup = bs4.BeautifulSoup(res.text, "html.parser")
  49.     content = soup.find_all(class_="s xst")

  50.     return content


  51. # 打开链接
  52. def open_url(url, cookie):
  53.     headers = {}

  54.     headers["User-Agent"] = "Mozilla/5.0"

  55.     if cookie != None:
  56.         headers["cookie"] = cookie
  57.    
  58.     res = requests.post(url, headers=headers)
  59.    
  60.     return res


  61. # 主函数
  62. def main(url, page, interval, cookie):   
  63.     # 用于清除文件里面的内容
  64.     with open("帖子.txt", "w", encoding="utf-8"):
  65.         pass

  66.     if page == 0:
  67.         res = open_url(url)
  68.         page = return_last(res)

  69.     subject_num = 1
  70.     judge = False   # 用于判断是否是最后一页,如果是,则不写入分隔线
  71.     method = 1  # 用于分辨使用哪种方法来分隔

  72.     if "&" not in url:
  73.         new_url = url.split("-")
  74.         
  75.         p = re.compile(r"\d")
  76.         num = p.findall(new_url[2])    # 用于翻页
  77.         num = int("".join(num))
  78.         
  79.         new_url[2] = str(num)+".html"
  80.         new_url = "-".join(new_url)
  81.         method = 1

  82.     else:
  83.         if "&page" not in url:
  84.             new_url = url
  85.             new_url += "&page="
  86.             num = 1
  87.         else:
  88.             new_url = url.split("=")
  89.             num = int(new_url[-1])

  90.             # 查找页数位置
  91.             new_url = url
  92.             p = re.compile(r"&page=")
  93.             index = p.search(new_url).end()

  94.             # 删除数字
  95.             new_url = list(new_url)
  96.             del new_url[index:]
  97.             
  98.             new_url = "".join(new_url)
  99.             
  100.         method = 2

  101.     page += num - 1
  102.               
  103.     while num <= page:
  104.         if num == page:
  105.             judge = True

  106.         content = ""

  107.         while not content:
  108.             res = open_url(new_url, cookie)
  109.             content = find_data(res)
  110.         
  111.         subject_num = write(content, subject_num, judge, url)

  112.         print(f"以爬取第 {num} 页...")

  113.         num += 1

  114.         if method == 1:
  115.             new_url = url.split("-")
  116.             new_url[2] = str(num)+".html"
  117.             new_url = "-".join(new_url)
  118.             
  119.         else:
  120.             new_url += str(num)

  121.         time.sleep(interval)

  122. if __name__ == "__main__":
  123.     try:
  124.         url = input("请输入板块地址:")
  125.         page = int(input('请输入爬取的页数("0"表示全部):'))
  126.         interval = eval(input("请输入爬取间隔:"))
  127.         
  128.         cookie = None

  129.         if input("是否使用授权(y/n):").lower() == "y":
  130.             cookie = input("请输入 cookie:")

  131.         main(url, page, interval, cookie)

  132.         print("爬取完毕!")
  133.         input()

  134.     except SystemExit:
  135.         pass
  136.         
  137.     except:
  138.         exceptionbox("爬取失败,请将以下错误报告和您输入的内容反馈给管理员:")
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-9 00:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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