写爬虫?前端er何必用python

前言

说起网络爬虫,很多人第一时间想到python,但爬虫并非只能用python实现,虽然网上大部分爬虫文章都在说python爬虫,但对于前端程序员来说,我觉得js才是最屌的(对于简单爬取任务来说,复杂的我暂时没碰到~),下面说说我的经验(是的,仅限本人经验),希望能给各位前端程序员带来一点新视角。

前置条件

  • 熟悉常用的js bom dom api
  • 会用chrome devtool

什么是爬虫

简单点,字面意思,爬虫就是用来爬取数据(文本、图片、视频等等)的代码脚本;

在第一次听爬虫的时候,感觉这个词碉堡了,学会了一定很酷!这也是我以前入坑python的主要原因。但搜索下科普文章/百科等等,还是有点云里雾里的感觉。其实我觉得了解一个概念从实际的需求出发更加容易理解,毕竟概念是人造的,没有概念前呢?下面根据真实事件改编:

需求一:获取豆瓣评分电影Top250的详细信息

需要获取以下表头信息,并存到本地/数据库/..

先不说怎么做到,但只要你用代码实现了这个需求,那你就是写了一个爬虫。

js爬虫思路实践

从哪里开始呢?首先,你要爬数据,就得先有目标,一般目标是一个网页,网页上有你想要的数据,一般网页数据多的时候都会分页请求数据,那必然就有规律!

1. 分析页面请求,找到数据来源,分析接口规律

简单分析下第一页/第二页接口请求,发现数据是以下接口返回的:

依此类推,第几页只是start参数不一样

2. 用代码模拟获取接口数据

代码模拟获取接口数据?那不就是调接口吗,这我熟,于是axios/fetch一顿撸,如下:

javascript 复制代码
fetch("https://movie.douban.com/top250?start=1")
  .then(function (response) {
    return response.text();
  })
  .then((r) => {
    console.log(333, r);
  });

放到console下跑下,数据不就拿到了!

3. 过滤处理提取数据

返回json数据还好处理,但这返回的是一个html文档啊,怎么过滤获取我们想要的数据呢?我们换个思路,对于处理html文档,dom api再合适不过了,但怎么用document对象方法呢,用iframe!

js 复制代码
const iframe = document.createElement("iframe");
iframe.onload = () => {
  console.log(111, iframe.contentWindow.document);
};
document.body.appendChild(iframe);
iframe.src = "https://movie.douban.com/top250?start=1";

放到console下跑下,拿到document对象了!

处理数据就要找到数据规律,这一步是灵魂。简单看下发现每部电影信息都在 li 标签里了,只需把对应文本提取出来即可。

提取文本?这我熟,一顿撸:

js 复制代码
// ... 接上面
iframe.onload = () => {
  const iDom = iframe.contentWindow.document;
  const itemList = iDom.querySelectorAll(".item");
  for (let i = 0; i < itemList.length; i++) {
    const item = itemList[i];
    // 电影详情链接
    const link = item.querySelector("a").href;
    // 图片链接
    const imageUrl = item.querySelector("img").src;
    // 影片名字
    const name = item.querySelector(".title").innerText;
    // 评分
    const rateNum = item.querySelector(".rating_num").innerText;
    //评价数
    const ratePerson = parseInt(
      item.querySelector(".star").lastChild.previousSibling.innerText
    );
    // 概况
    const about = item.querySelector(".quote")?.innerText;
    // 相关信息
    const desc = item.querySelector(".bd").querySelector("p").innerText;
    console.log(111, link, imageUrl, name, rateNum, ratePerson, about, desc);
  }
};
// ...

跑下,没问题!

最终全部数据:

4. 存储/下载/..数据

最后,拿到数据后,需要保存起来,这一步我保存为json(其他格式直接用第三方库!)

全部代码:

js 复制代码
const top250 = {};
let currentPage = 1;
const iframe = document.createElement("iframe");
iframe.onload = () => {
  const iDom = iframe.contentWindow.document;
  const itemList = iDom.querySelectorAll(".item");
  for (let i = 0; i < itemList.length; i++) {
    const item = itemList[i];
    // 电影详情链接
    const link = item.querySelector("a").href;
    // 图片链接
    const imageUrl = item.querySelector("img").src;
    // 影片名字
    const name = item.querySelector(".title").innerText;
    // 评分
    const rateNum = item.querySelector(".rating_num").innerText;
    //评价数
    const ratePerson = parseInt(
      item.querySelector(".star").lastChild.previousSibling.innerText
    );
    // 概况
    const about = item.querySelector(".quote")?.innerText;
    // 相关信息
    const desc = item.querySelector(".bd").querySelector("p").innerText;
    top250[name] = { link, imageUrl, name, rateNum, ratePerson, about, desc };
  }

  // 启动下一页
  if (currentPage <= 10) {
    currentPage++;
    iframe.src = `https://movie.douban.com/top250?start=${25 * (currentPage - 1)}`;
  } else {
    downloadText("test.json", JSON.stringify(top250));
  }
};
document.body.appendChild(iframe);
iframe.src = "https://movie.douban.com/top250?start=0";

function downloadText(fileName, text) {
  const url = window.URL || window.webkitURL || window;
  const blob = new Blob([text]);
  const saveLink = document.createElement("a");
  saveLink.href = url.createObjectURL(blob);
  // 设置 download 属性
  saveLink.download = fileName;
  saveLink.click();
  url.revokeObjectURL(saveLink.href);
}

跑下,收工!

打开文件,格式下数据(为了好看):

总结

对于爬虫任务,只要抓住本质需求,掌握分析的套路,用什么实现都可以。但对于前端程序员,上面的接口调用,dom元素获取,我们有天然的优势,属于基操呀,又何必去入坑python,去学另一套语言的类 'dom' 接口呢(python过滤数据更多是用正则匹配,有点繁琐)!

更多

相关推荐
kisloy11 小时前
【爬虫入门第13讲】Scrapy 框架深度解析(四)核心配置与自定义扩展
网络·爬虫·scrapy
TlSfoward1 天前
TLSFoward 能帮你看到什么 TLSFOWARD抓包工具
服务器·爬虫·网络协议·https
2501_916007471 天前
Python实现HTTPS爬虫的完整指南:使用requests、BeautifulSoup、Selenium和Scrapy
爬虫·python·ios·小程序·https·uni-app·iphone
'pi%'1 天前
LangGraph 多智能体实战:搭建电力政策跟踪 Agent,实现网页爬虫、OCR 与 PDF 文档自动化解析
爬虫·pdf·ocr
杨先生哦1 天前
【2026热端攻防系列 11/12】前端AI风控攻防实战:验证码缺陷、人机验证绕过、智能爬虫对抗与企业智能风控加固方案
前端·人工智能·笔记·爬虫·安全
久久学姐1 天前
Python开发爬虫的常用技术架构
爬虫·python·http·框架·数据存储
tang777891 天前
分布式爬虫优化指南:如何用代理IP把采集效率提升300%
分布式·爬虫·python·tcp/ip·分布式爬虫·爬虫代理·代理ip
二十雨辰2 天前
[爬虫]-request
爬虫
狗都不学爬虫_3 天前
AI逆向 - 99aq中心滑块验证+登录(wasm纯算)
爬虫·python·网络爬虫
hyf3266334 天前
泛程序:从零开始搭建稳定程序项目框架
运维·服务器·爬虫·百度·seo