经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Python爬虫实战系列3:今日BBNews编程新闻采集
来源:cnblogs  作者:Python魔法师  时间:2024/3/15 9:01:05  对本文有异议

一、分析页面

打开今日BBNews网址 https://news.bicido.com ,下拉选择【编程】栏目

首页.png

1.1、分析请求

F12打开开发者模式,然后点击Network后点击任意一个请求,Ctrl+F开启搜索,输入标题Apache Doris 2.1.0 版本发布 ,开始搜索

分析请求.png

搜索结果显示直接返回的json格式,那就so easy了,直接copy curl,然后将curl 转换为Python代码,运行。

推荐个curl转Python代码的在线工具:https://curlconverter.com/

curl_to_python.png

二、代码实现

直接将curl 转换后的Python代码做下修改,然后调试运行即可。

完整代码

  1. # -*- coding: utf-8 -*-
  2. import os
  3. import sys
  4. from datetime import datetime
  5. import requests
  6. opd = os.path.dirname
  7. curr_path = opd(os.path.realpath(__file__))
  8. proj_path = opd(opd(opd(curr_path)))
  9. sys.path.insert(0, proj_path)
  10. from app.conf.conf_base import USERAGENT
  11. spider_config = {
  12. "name_en": "https://news.bicido.com",
  13. "name_cn": "今日BBNews"
  14. }
  15. class Bbnews:
  16. def __init__(self):
  17. self.headers = {
  18. 'referer': 'https://news.bicido.com/',
  19. 'user-agent': USERAGENT
  20. }
  21. def get_group(self):
  22. url = 'https://news.bicido.com/api/config/news_group/'
  23. content = requests.get(url=url, headers=self.headers)
  24. content = content.json()
  25. return content
  26. def get_news(self):
  27. groups = self.get_group()
  28. news_type = []
  29. for group in groups:
  30. if group['name'] == '编程':
  31. news_type = group['news_types']
  32. result = []
  33. for news_type in news_type:
  34. type_id = news_type['id']
  35. url = f'https://news.bicido.com/api/news/?type_id={type_id}'
  36. content = requests.get(url, headers=self.headers)
  37. news_list = content.json()
  38. for new in news_list:
  39. result.append({
  40. "news_title": str(new['title']),
  41. "news_date": datetime.now(),
  42. "source_en": spider_config['name_en'],
  43. "source_cn": spider_config['name_cn'],
  44. })
  45. return result
  46. def main():
  47. bbnews = Bbnews()
  48. results = bbnews.get_news()
  49. print(results)
  50. if __name__ == '__main__':
  51. main()

总结

  1. 今日BBNews页面没反爬策略,比较简单,拿来即用
  2. 本文介绍了curl to Python的工具,方便好用。

本文章代码只做学习交流使用,作者不负责任何由此引起的法律责任。

各位看官,如对你有帮助欢迎点赞,收藏,转发,关注公众号【Python魔法师】获取更多Python魔法~

qrcode.jpg

原文链接:https://www.cnblogs.com/meet/p/18068021

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号