首页 > 编程语言 >Python 爬虫,Nendo 网站作品信息采集爬虫源码!

Python 爬虫,Nendo 网站作品信息采集爬虫源码!

时间:2024-01-07 12:33:50浏览次数:114  
标签:img get Python h1 tree 爬虫 源码 print path


简单的网站写爬虫就跟流水线加工一样,抄抄改改,没有问题就直接上了,直接了当省事,又是一篇没有营养的水文。一个比较简单的爬虫,适合练手学习使用,主要是爬取和采集网站的作品信息,包括标题、内容及图片,其中图片采用了多线程爬取。

Python 爬虫,Nendo 网站作品信息采集爬虫源码!_开发语言

考虑到外网爬取,所以采用了三次访问超时重试的机制,同时对于详情页的爬取采用了报错机制跳过处理,适合新人学习爬取使用。小日子的网站随便爬,加大力度,使劲搞,适合 Python 爬虫新人练手使用和学习,如果你正在找练手网站,不妨尝试爬取下载数据。

Python 爬虫,Nendo 网站作品信息采集爬虫源码!_爬虫_02

详情页关键节点处理的代码:

tree = etree.HTML(html)
    h1=tree.xpath('//h1[@class="entry-title"]/text()')[0]
    pattern = r"[\/\\\:\*\?\"\<\>\|]"
    h1=re.sub(pattern, "_", h1)  # 替换为下划线
    print(h1)
    path = f'{h1}/'
    os.makedirs(path, exist_ok=True)
    print(f">> 生成保存目录 {h1} 文件夹成功!")
    ptexts=tree.xpath('//div[@class="main-text"]/p/text()')
    ptext=''.join(ptexts)
    print(ptext)
    with open(f'{path}{h1}.txt','w',encoding='utf-8') as f:
        f.write(f'{h1}\n{ptext}')
    print(f">> 保存 {h1}.txt 文件成功!")
    imgs=tree.xpath('//div[@class="slider-for"]/div[@class="sp-slide"]/img/@src')

文章最后附上早期写的,看看有没有差距和不同之处呢?!

附上完整源码仅供参考学习使用。

# -*- coding: UTF-8 -*-
# @公众号:eryeji
# https://www.nendo.jp/jp/works/

import requests
from lxml import etree
import time
import random
import re
import threading
import os


def get_ua():
    ua_list = [
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36Chrome 17.0',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
        'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0Firefox 4.0.1',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
        'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
        'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
        'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
    ]
    ua=random.choice(ua_list)
    return ua


def get_hrefs():
    url="https://www.nendo.jp/jp/works/"
    headers={
        "User-Agent":get_ua()
    }
    response=requests.get(url=url,headers=headers,timeout=6)
    print(response.status_code)
    html = response.content.decode('utf-8')
    #print(html)
    tree = etree.HTML(html)
    hrefs = tree.xpath('//div[@class="entry-content"]/a/@href')
    print(len(hrefs))
    print(hrefs)
    for href in hrefs:
        get_detail(href)
        time.sleep(3)



def get_detail(href):
    headers = {
        "User-Agent": get_ua()
    }
    response = requests.get(url=href, headers=headers, timeout=6)
    print(response.status_code)
    html = response.content.decode('utf-8')
    #print(html)
    tree = etree.HTML(html)
    h1=tree.xpath('//h1[@class="entry-title"]/text()')[0]
    pattern = r"[\/\\\:\*\?\"\<\>\|]"
    h1=re.sub(pattern, "_", h1)  # 替换为下划线
    print(h1)
    path = f'{h1}/'
    os.makedirs(path, exist_ok=True)
    print(f">> 生成保存目录 {h1} 文件夹成功!")
    ptexts=tree.xpath('//div[@class="main-text"]/p/text()')
    ptext=''.join(ptexts)
    print(ptext)
    with open(f'{path}{h1}.txt','w',encoding='utf-8') as f:
        f.write(f'{h1}\n{ptext}')
    print(f">> 保存 {h1}.txt 文件成功!")
    imgs=tree.xpath('//div[@class="slider-for"]/div[@class="sp-slide"]/img/@src')
    print(len(imgs))
    print(imgs)
    down_imgs(path, imgs)




# 3次重试
def get_resp(url):
    i = 0
    while i < 4:
        try:
            headers = {
               "User-Agent":get_ua()
            }
            response = requests.get(url, headers=headers, timeout=10)
            print(response.status_code)
            return response
        except requests.exceptions.RequestException:
            i += 1
            print(f">> 获取网页出错,6S后将重试获取第:{i} 次")
            time.sleep(i * 2)



def down_imgs(path,imgs):
    threadings = []
    for img in imgs:
        t = threading.Thread(target=get_img, args=(path,img))
        threadings.append(t)
        t.start()

    for x in threadings:
        x.join()

    print(f"恭喜,多线程下载图片完成!")


#下载图片
def get_img(path,img_url):
    img_name = img_url.split('/')[-1]
    r = get_resp(img_url)
    time.sleep(1)
    with open(f'{path}{img_name}', 'wb')as f:
        f.write(r.content)
    print(f">> {img_name}下载图片成功")


def main():
    get_hrefs()




if __name__=='__main__':
    main()

附早期写的:

Python爬虫,超简单nendo官网作品图片爬虫demo

Python 爬虫,Nendo 网站作品信息采集爬虫源码!_爬虫_03

·················END·················

你好,我是二大爷,

革命老区外出进城务工人员,

互联网非早期非专业站长,

喜好python,写作,阅读,英语

不入流程序,自媒体,seo . . .


Python 爬虫,Nendo 网站作品信息采集爬虫源码!_Windows_04

Python 爬虫,Nendo 网站作品信息采集爬虫源码!_html_05

关注我的都变秃了

说错了,都变强了!

不信你试试

Python 爬虫,Nendo 网站作品信息采集爬虫源码!_爬虫_06

扫码关注最新动态

公众号ID:eryeji

标签:img,get,Python,h1,tree,爬虫,源码,print,path
From: https://blog.51cto.com/u_15200177/9133840

相关文章

  • slf4j+logback源码加载流程解析
    slf4j绑定logback源码解析Loggerlog=LoggerFactory.getLogger(LogbackDemo.class);如上述代码所示,在项目中通常会这样创建一个Logger对象去打印日志。然后点进去,会走到LoggerFactory的getILoggerFactory()方法,如下代码所示。publicstaticILoggerFactorygetILoggerFactory()......
  • datetime毫秒python
    实现datetime毫秒Python引言在Python中,datetime模块提供了处理日期和时间的功能。然而,datetime模块默认只提供精确到秒的时间戳,如果需要精确到毫秒的时间戳,我们需要对datetime模块进行一些扩展。本文将指导你如何实现在Python中获取精确到毫秒的时间。流程概述下面是实现dat......
  • conda create创建环境 指定python版本
    使用condacreate创建环境指定python版本在开发Python程序时,我们经常会遇到多个项目使用不同的Python版本的情况。为了解决这个问题,我们可以使用Anaconda提供的conda命令来创建虚拟环境,并在创建环境时指定所需的Python版本。这篇文章将介绍如何使用condacreate命令创建环境并指......
  • class ABC python
    如何实现Python中的类(classABC)作为一名经验丰富的开发者,我很高兴能教给你如何在Python中实现一个类(classABC)。下面是一个简单的步骤表格,将指导你完成这个过程。步骤描述步骤1定义一个类步骤2添加属性和方法步骤3创建类的实例步骤4使用类的属性和方法......
  • 书籍推荐-《机器人编程:使用树莓派3和Python构建和控制自主机器人》
    以下内容来自公众号【一点人工一点智能】编辑:东岸因为@一点人工一点智能书籍:LearnRoboticsProgramming:BuildandcontrolautonomousrobotsusingRaspberryPi3andPython作者:DannyStaple出版:PacktPublishing01书籍介绍我们生活在一个最复杂或重复的任务都是自动化......
  • 医学检验科LIS系统,LIS检验系统源码
    LIS系统功能模块字典模块:系统参数、标本管理、试管管理、平台设备管理、送检类型管理、检验项目管理、检查组合管理、项目转换管理。报告模块:试管条码打印、检验报告管理、报告登记、报告接收、报告打印、历史数据查询、数据存根、报告审核。质控模块:质控品管理、质控规则管理......
  • js和python的接口api怎么开发
    在JavaScript(JS)和Python之间开发接口(API)时,可以使用多种方法,具体取决于你的需求和偏好。以下是一些常见的方法:RESTfulAPI:RESTful(RepresentationalStateTransfer)是一种设计风格,通过HTTP协议进行通信。你可以使用Node.js(JavaScript)和Flask/Django(Python)等框架来实现RESTfulAPI。在......
  • Python教程(20)——python面向对象编程基本概念
    面向对象(Object-oriented)是一种常用的程序设计思想,它以对象作为程序的基本单元,将数据和操作封装在一起,通过对象之间的交互来实现程序的功能。在面向对象编程中,将问题抽象成对象,而对象可以拥有属性(数据)和方法(操作)。对象可以被看作是现实世界中的实体或概念,具有某种特定的状态和行......
  • Python创建virtualenv(虚拟环境)方法
    一前言   需求:      --公司之有一台服务器      -目前运行这一个5年前开发的Django项目,基于1.5      -现在要基于Django2.0开发一套程序      -无法卸载原来的版本,必须还要安装新版本二通过virtualenv软件创建安装:      ......
  • python自然语言处理
    #使用NLTK进行文本处理importnltkfromnltk.tokenizeimportword_tokenizepath=r"E:\Code\Python\录制\python-crawler\作业\test"nltk.data.path.append(path)#添加你想要的文件夹路径#确保资源文件下载到指定文件夹nltk.download('punkt',download_dir=path)......