首页 > 其他分享 >一条爬虫抓取一个小网站所有数据

一条爬虫抓取一个小网站所有数据

时间:2023-10-10 23:04:44浏览次数:31  
标签:return 网站 self list 爬虫 抓取 content article font

一条爬虫抓取一个小网站所有数据

今天闲来无事,写一个爬虫来玩玩。在网上冲浪的时候发现了一个搞笑的段子网,发现里面的内容还是比较有意思的,于是心血来潮,就想着能不能写一个Python程序,抓取几条数据下来看看,一不小心就把这个网站的所有数据都拿到了。

一条爬虫抓取一个小网站所有数据_html

这个网站主要的数据都是详情在HTML里面的,可以采用lxml模块的xpath对HTML标签的内容解析,获取到自己想要的数据,然后再保存在本地文件中,整个过程是一气呵成的。能够抓取到一页的数据之后,加一个循环就可以抓取到所有页的数据,下面的就是数据展示。

一条爬虫抓取一个小网站所有数据_数据_02

废话少说,直接上Python代码

import requests
import csv
from lxml import etree
import time


class Page:

    def __init__(self):
        self.pre_url = "https://www.biedoul.com"
        self.start_page = 1
        self.end_page = 15233

    def askHTML(self, current_page, opportunity):
        print(
            "=============================== current page => " + str(current_page) + "===============================")
        try:

            pre_url = self.pre_url + "/index/" + str(current_page)
            page = requests.get(url=pre_url)
            html = etree.HTML(page.content)
            articles = html.xpath('/html/body/div/div/div/dl')
            return articles
        except Exception as e:
            if opportunity > 0:
                time.sleep(500)
                print(
                    "=============================== retry => " + str(opportunity) + "===============================")
                return self.askHTML(current_page, opportunity - 1)
            else:
                return None

    def analyze(self, articles):
        lines = []
        for article in articles:
            data = {}
            data["link"] = article.xpath("./span/dd/a/@href")[0]
            data["title"] = article.xpath("./span/dd/a/strong/text()")[0]
            data["content"] = self.analyze_content(article)
            picture_links = article.xpath("./dd/img/@src")
            if (picture_links is not None and len(picture_links) > 0):
                # print(picture_links)
                data["picture_links"] = picture_links
            else:
                data["picture_links"] = []

            # data["good_zan"] = article.xpath("./div/div/a[@class='pinattn good']/p/text()")[0]
            # data["bad_bs"] = article.xpath("./div/div/a[@class='pinattn bad']/p/text()")[0]
            data["good_zan"] = self.analyze_zan(article, "good")
            # article.xpath("./div/div/a[@class='pinattn good']/p/text()")[0]
            data["bad_bs"] = self.analyze_zan(article, "bad")
            # article.xpath("./div/div/a[@class='pinattn bad']/p/text()")[0]
            lines.append(data)
        return lines

    # 解析文章内容
    def analyze_content(self, article):
        # 1. 判断dd标签下是否为文本内容
        content = article.xpath("./dd/text()")
        if content is not None and len(content) > 0 and not self.is_empty_list(content):
            return content

        content = []
        p_list = article.xpath("./dd")
        for p in p_list:
            # 2. 判断dd/.../font标签下是否为文本内容
            if len(content) <= 0 or content is None:
                fonts = p.xpath(".//font")
                for font_html in fonts:
                    font_content = font_html.xpath("./text()")
                    if font_content is not None and len(font_content) > 0:
                        content.append(font_content)

            # 3. 判断dd/.../p标签下是否为文本内容
            if len(content) <= 0 or content is None:
                fonts = p.xpath(".//p")
                for font_html in fonts:
                    font_content = font_html.xpath("./text()")
                    if font_content is not None and len(font_content) > 0:
                        content.append(font_content)

        return content

    def analyze_zan(self, article, type):
        num = article.xpath("./div/div/a[@class='pinattn " + type + "']/p/text()")
        if num is not None and len(num) > 0:
            return num[0]
        return 0

    def do_word(self):
        fieldnames = ['index', 'link', 'title', 'content', 'picture_links', 'good_zan', 'bad_bs']
        with open('article.csv', 'a', encoding='UTF8', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            # writer.writeheader()
            for i in range(self.start_page, self.end_page):
                articles = self.askHTML(i, 3)
                if articles is None:
                    continue
                article_list = self.analyze(articles)
                self.save(writer, article_list)

    # 保存到文件中
    def save(self, writer, lines):
        print("##### 保存中到文件中...")
        # python2可以用file替代open
        print(lines)
        writer.writerows(lines)
        print("##### 保存成功...")

    def is_empty_list(self, list):
        for l in list:
            if not self.empty(l):
                return False
        return True

    def empty(self, content):
        result = content.replace("\r", "").replace("\n", "")
        if result == "":
            return True
        return False

    # 递归解析文章内容
    def analyze_font_content(self, font_html, depth):
        content = []
        print(depth)
        font_content_list = font_html.xpath("./font/text()")
        if font_content_list is not None and len(font_content_list) > 0 and not self.is_empty_list(font_content_list):
            for font_content in font_content_list:
                content.append(font_content)
        else:
            if depth < 0:
                return []
            return self.analyze_font_content(font_html.xpath("./font"), depth - 1)

        return content


if __name__ == '__main__':
    page = Page()
    page.do_word()

在运行下面的代码之前,需要先按照好requests、lxml两个模块,安装命令为:

pip installl requests
pip install lxml

大家对这个爬虫有什么疑问,欢迎给我留言。如果大家对于我这个爬虫创意还不错的话,记得关注微信公众号【智享学习】哟,后续我会分享更多有意思的编程项目。

本文由博客一文多发平台 OpenWrite 发布!

标签:return,网站,self,list,爬虫,抓取,content,article,font
From: https://blog.51cto.com/u_14725510/7800539

相关文章

  • FIrefox不能登陆简书、segmentfault等网站
    简书、segmentfault这些网站的登录按钮显示灰色不能点击原因是FIrefox的开启了增强型跟踪保护,关闭该选项即可。EnhancedTrackingProtectioninFirefoxfordesktop:当您处于严格增强跟踪保护状态时,您可能会在某些网站上遇到损坏。这是因为跟踪器隐藏在某些内容中。例如,网......
  • 利用Python爬虫打造SEO智能关键词聚合
    在当今互联网的竞争激烈时代,网站的SEO优化至关重要。而关键词是SEO优化的核心,选择恰当的关键词能够带来更多的流量和用户。本文将为您揭秘一项SEO黑科技:如何利用Python爬虫打造智能关键词聚合工具。通过这个工具,您可以快速地扫描和聚合与您网站相关的关键词,为您的SEO优化提供更准确......
  • 新手如何快速上手HTTP爬虫IP?
    对于刚接触HTTP爬虫IP的新手来说,可能会感到有些困惑。但是,实际上HTTP爬虫IP并不复杂,只要掌握了基本的操作步骤,就可以轻松使用。本文将为新手们提供一个快速上手HTTP爬虫IP的入门指南,帮助您迅速了解HTTP爬虫IP的基本概念和操作方法。第一步:了解HTTP爬虫IP的基本概念HTTP爬虫IP是一种......
  • 通过社工进网站后台
    通过社工进网站后台记录一次通过简单社工获取信息后进入后台的经过。打开思路,利用我们所有能够捕获的信息并串联起来。0X0开始:打开网站发现是一个登录网站随便输入账号密码,发现有用户名枚举:0X1获取icp备案企业:通过爆破用户名,然后爆破密码始终没有进去,于是开始了社工利......
  • Typecho博客网站迁移:MySQL ➡️ MarialDB
    目录1.引言2.Typecho的自定义配置迁移3.数据库迁移:MySQL->MarialDB3.1在原服务器中备份并导出数据库文件3.2将“backupdb.sql”文件拷贝至新服务器并导入数据4.Nginx配置5.Handsome主题操作1.引言由于服务、价格等因素更换云服务器是很常见的情况,本文记录了Typecho博......
  • 【持续更新】资源搜索网站汇总
    以下汇总了在用的资源搜索网站资源搜索网站:【1】黑洞导航:https://hddh.link【2】阿里云盘分享大集合-长期更新-建议收藏内有几千T资源https://docs.qq.com/sheet/DVXp5Q2dRTVRXb2VS?tab=oz0lgd ......
  • 【持续更新】work网站汇总
    工作中会用到的网站汇总,好的网站能给予我们灵感。以防忘记,特此记录。1 程序员网站:【1】stackoverflow是全球最大的编程问答网站,英文网页https://stackoverflow.com/【2】原型来自于国外最大的程序员问答社区StackOverflow,中文网页https://segmentfault.com/【3】Githubh......
  • 【node爬虫】node爬虫实用教程
    准备工作通过指令npminit初始化文件夹,会获得package.json项目说明书。爬虫必备工具:cheerio;通过在终端输入npmicheerio,即可将文件装到项目里。cheerio 是 jquery 核心功能的一个快速灵活而又简洁的实现,主要是为了用在服务器端需要对 DOM 进行操作的地方。大家可以简......
  • 花瓣网爬虫
    fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByimporttimeimportosBASE_URL="https://huaban.com/search?q={keyword}&sort=all&type=board&category=industrial_design"defsearch_and_save_links(driver,keyword,......
  • 异步爬虫实战:实际应用asyncio和aiohttp库构建异步爬虫
    在网络爬虫的开发中,异步爬虫已经成为一种非常流行的技术。它能够充分利用计算机的资源,提高爬虫效率,并且能够处理大量的运算请求。Python中的asyncio和aiohttp库提供了强大的异步爬虫支持,使得开发者能够轻松构建高效的异步爬虫。什么是异动爬虫?为什么要使用自动爬虫?异步爬虫是一......