当前位置:   article > 正文

使用Django开发爬虫系统_django调用request爬虫

django调用request爬虫

在本文中,我们将介绍如何使用Django开发一个简单但功能强大的爬虫系统。我们将使用Python编写爬虫,并将爬取到的数据存储到Django模型中,然后通过Django的管理页面管理这些数据。

1. 介绍

爬虫系统用于从互联网上收集信息,常用于数据分析、搜索引擎等领域。我们选择使用Django作为开发框架,因为它提供了强大的数据库管理和Web开发功能,能够帮助我们快速搭建一个稳健的爬虫系统。

2. 环境设置

首先确保您已经安装了Python,并使用pip安装了Django和其他必要的库:

pip install django requests beautifulsoup4

3. 创建Django项目

使用Django命令行工具创建一个新的项目:

  1. django-admin startproject mycrawler
  2. cd mycrawler

4. 定义模型

models.py文件中定义一个模型来存储爬取到的数据:

  1. from django.db import models
  2. class Article(models.Model):
  3. title = models.CharField(max_length=100)
  4. content = models.TextField()
  5. created_at = models.DateTimeField(auto_now_add=True)
  6. def __str__(self):
  7. return self.title

运行数据库迁移命令以创建数据库表:

  1. python manage.py makemigrations
  2. python manage.py migrate

5.具体代码

  1. from django.shortcuts import render
  2. from django.http import HttpResponse
  3. from django.http import JsonResponse
  4. import json
  5. import bag
  6. import re
  7. from bs4 import BeautifulSoup
  8. from tqdm import tqdm
  9. import time
  10. import random
  11. def index(request):
  12. return render(request, 'index.html')
  13. def get_url(city_name, item):
  14. session = bag.session.create_session()
  15. for cookie in bag.Bag.read_json(r'./static/cookies.json'):
  16. session.cookies.set(cookie['name'], cookie['value'])
  17. session.headers['Connection'] = 'close'
  18. js_data = bag.Bag.read_json('./static/city.json')
  19. judge = js_data.get(city_name)
  20. if judge:
  21. city = judge.split('/')[-1]
  22. js_data1 = bag.Bag.read_json('./static/menu.json')
  23. judge1 = js_data1.get(item)
  24. if judge1:
  25. return judge1.format(city), session
  26. def get_shops(request):
  27. if request.method == 'POST':
  28. try:
  29. data = json.loads(request.body)
  30. if not bool(data.get('city')) and not bool(data.get('shopLink')):
  31. return JsonResponse({'message': '请选择城市'}, status=200)
  32. elif not bool(data.get('city')) and bool(data.get('shopLink')): # 处理传入具体链接后续开发
  33. pass
  34. else:
  35. url, session = get_url(data.get('city'), data.get('selectedType'))
  36. def get_types(): # 正常传参
  37. pattern = re.compile(r'<a.*?href="(.*?)".*?<span>(.*?)</span></a>', re.S)
  38. if bool(url):
  39. resp = session.get(url)
  40. html = BeautifulSoup(resp.text, 'html.parser')
  41. soup = html.findAll('div', id='classfy')
  42. links = re.findall(pattern, str(soup))
  43. return links
  44. else:
  45. return None
  46. def get_shop():
  47. links = get_types()
  48. pattern = re.compile(r'<div class="tit">.*?<a.*?data-shopid="(.*?)".*?href="(.*?)".*?title="(.*?)"'
  49. r'(?:.*?<div class="star_icon">.*?<span class="(.*?)"></span>.*?<b>(.*?)</b>)?'
  50. r'(?:.*?<b>(.*?)</b>)?'
  51. r'(?:.*?<div class="tag-addr">.*?<span class="tag">(.*?)</span>.*?<em class="sep">.*?<span class="tag">(.*?)</span>)?',
  52. re.S)
  53. number = re.compile(r'data-ga-page="(.*?)"', re.S)
  54. result = []
  55. print(len(links))
  56. for link in links[11:12]: # 获取第一页
  57. resp = session.get(link[0])
  58. time.sleep(random.randint(1, 10))
  59. page = [int(i) for i in re.findall(number, resp.text)]
  60. page_num = sorted(page, reverse=True)[0]
  61. html = BeautifulSoup(resp.text, 'html.parser')
  62. soup = html.findAll('li', class_='')
  63. for i in soup:
  64. for j in re.findall(pattern, str(i)):
  65. result.append(j)
  66. if page_num >= 2: # 获取第一页往后
  67. for count in tqdm(range(page_num)):
  68. try:
  69. resp1 = session.get(link[0] + 'p{}'.format(count + 1))
  70. time.sleep(random.randint(1, 5))
  71. # time.sleep(0.5)
  72. html1 = BeautifulSoup(resp1.text, 'html.parser')
  73. soup1 = html1.findAll('li', class_='')
  74. for k in soup1:
  75. info = pattern.search(str(k))
  76. if info:
  77. groups = list(info.groups())
  78. for i in range(len(groups)):
  79. if not groups[i]:
  80. groups[i] = 'null'
  81. result.append(tuple(groups))
  82. except Exception as e:
  83. print(e)
  84. continue
  85. else:
  86. pass
  87. return result
  88. end = get_shop()
  89. bag.Bag.save_excel(end, f'./{data.get("city")}_{data.get("selectedType")}.xlsx')
  90. return JsonResponse({'message': 'Data received successfully'}, status=200)
  91. except json.JSONDecodeError as e:
  92. return JsonResponse({'error': 'Invalid JSON format'}, status=400)
  93. else:
  94. return JsonResponse({'error': 'Only POST requests are allowed'}, status=405)

index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>首页</title>
  6. <link rel="stylesheet" href="../static/css/page.css" />
  7. <script type="text/javascript" src="../static/js/jquery.min.js" ></script>
  8. <script type="text/javascript" src="../static/js/index.js" ></script>
  9. </head>
  10. <body>
  11. <div class="left">
  12. <div class="bigTitle">爬虫管理系统</div>
  13. <div class="lines">
  14. <div onclick="pageClick(this)" data-html="/text.html" data-title="文本爬虫"><img src="../static/img/icon-1.png" />文本爬虫</div>
  15. <div onclick="pageClick(this)" data-html="/image.html" data-title="图片爬虫"><img src="../static/img/icon-2.png" />图片爬虫</div>
  16. <div onclick="pageClick(this)" data-html="/music.html" data-title="音乐爬虫"><img src="../static/img/icon-3.png" />音乐爬虫</div>
  17. <div onclick="pageClick(this)" data-html="/video.html" data-title="视频爬虫"><img src="../static/img/icon-4.png" />视频爬虫</div>
  18. </div>
  19. </div>
  20. <div class="top">
  21. <div class="leftTiyle" id="flTitle">基于python实现的网络爬虫</div>
  22. <div class="thisUser">当前用户:互联网民工</div>
  23. </div>
  24. <div class="content" id="contentDiv"></div>
  25. <script>
  26. function pageClick(element) {
  27. var clickedElement = $(element);
  28. $('#contentDiv').empty();
  29. var htmlPath = clickedElement.attr('data-html');
  30. var pageTitle = clickedElement.attr('data-title');
  31. $.ajax({
  32. url: htmlPath,
  33. dataType: 'html',
  34. success: function (data) {
  35. $('#contentDiv').html(data);
  36. $('#flTitle').text(pageTitle); // 设置标题
  37. },
  38. error: function (xhr, status, error) {
  39. // 处理加载失败的情况
  40. }
  41. });
  42. }
  43. $(document).ready(function() {
  44. var defaultContent = "欢迎使用爬虫管理系统!请点击左侧功能以查看详细内容。"
  45. $('#contentDiv').html(defaultContent);
  46. });
  47. </script>
  48. </body>
  49. </html>

6. 部署

将Django应用部署到生产环境时,请确保使用安全的方法,并考虑使用Docker进行容器化部署,使用Nginx和Gunicorn进行Web服务器和应用服务器的配置等。

7. 体验地址

爬虫管理系统

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/939893
推荐阅读
相关标签
  

闽ICP备14008679号