首页 > 其他分享 >爬虫案例

爬虫案例

时间:2024-03-31 17:12:58浏览次数:21  
标签:__ title url text list 爬虫 案例 div

BS爬取笔趣阁小说数据

# -*- coding: utf-8 -*-
# author : heart
# blog_url : https://www.cnblogs.com/ssrheart/
# time : 2024/3/30
import random
import time

import requests
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
import os

headers = {
    'User-Agent': UserAgent().random,
}
proxies = {
    'http': 'http://221.6.139.190:9002'
}


def spider_title(url):
    response = requests.get(url=url, headers=headers, proxies=proxies).text

    soup = BeautifulSoup(response, 'lxml')

    dd_list = soup.find_all('div', class_='listmain')[0].find_all('dd')
    title_list = []
    for i in dd_list:
        if '<<---展开全部章节--->>' in i.text:
            continue
        href = i.a.get('href')
        href1 = 'https://www.bqgbb.cc' + href
        title = i.a.text
        title_list.append({
            'href': href1,
            'title': title
        })
    return title_list


def spider_content(url):
    response = requests.get(url=url, headers=headers, proxies=proxies).text
    soup = BeautifulSoup(response, 'lxml')
    div_list = soup.find_all('div', class_='Readarea ReadAjax_content')[0].text
    content = div_list
    return content


def save(title, content):
    base_dir = os.path.dirname(__file__)
    wenjian = os.path.join(base_dir, 'xiaoshuo')
    os.makedirs(wenjian, exist_ok=True)
    lujing = os.path.join(wenjian, f'{title}.txt')
    with open(lujing, 'w', encoding='utf-8') as f:
        f.write(content)


def main():
    title = spider_title(url='https://www.bqgbb.cc/book/11174/')
    for index, data in enumerate(title, start=1):
        title = data['title']
        href = data['href']
        time.sleep(random.randint(1,3))
        content = spider_content(url=href)
        save(title, content)
        print(f'{title}下载完成')


if __name__ == '__main__':
    main()

xpath爬取豆瓣TOP250数据

  • 使用xpath
# -*- coding: utf-8 -*-
# author : heart
# blog_url : https://www.cnblogs.com/ssrheart/
# time : 2024/3/31

import requests
from fake_useragent import UserAgent
from lxml import etree


class SpiderDB():
    def __init__(self):
        self.headers = {
            'User-Agent': UserAgent().random,
        }
        self.proxies = {
            'http': 'http://221.6.139.190:9002'
        }

    def spider_tag(self):
        tagurl_list = []
        for i in range(0, int(250 / 25)):
            if i == 0:
                tag_url = f'https://movie.douban.com/top250'
                tagurl_list.append(tag_url)
            else:
                tag_url = f'https://movie.douban.com/top250?start={i * 25}'
                tagurl_list.append(tag_url)
        return tagurl_list

    def spider_info(self, url):
        # print(url) # https://movie.douban.com/top250
        response = requests.get(url=url, headers=self.headers, proxies=self.proxies).text
        tree = etree.HTML(response)

        info = tree.xpath('//li/div[@class="item"]/div[@class="info"]')
        data_list = []
        for i in info:
            try:
                title = i.xpath('./div[1]/a/span[1]/text()')[0].strip()
            except:
                title = ''
            try:
                title_eng = i.xpath('./div[1]/a/span[2]/text()')[0].replace('\xa0', '').strip()
            except:
                title_eng = ''
            try:
                other_title = i.xpath('./div[1]/a/span[3]/text()')[0].replace('\xa0', '').strip()
            except:
                other_title = ''

            actor = i.xpath('./div[2]/p/text()')[0].replace('\xa0', '').strip()
            publish_time = i.xpath('./div[2]/p/text()')[1].replace('\xa0', '').strip()

            score = i.xpath('./div[2]/div/span[2]/text()')[0]
            pingjia_people = i.xpath('./div[2]/div/span[4]/text()')[0][0:-3]
            try:
                quote = i.xpath('./div[2]/p[@class="quote"]/span/text()')[0]
            except:
                quote = ''
            data_list.append({
                'title': title,
                'title_eng': title_eng,
                'other_title': other_title,
                'actor': actor,
                'publish_time': publish_time,
                'score': score,
                'pingjia_people': pingjia_people,
                'quote': quote,
            })
        # print(data_list)
        return data_list

    def main(self):
        tag_url = self.spider_tag()
        data_list_all = []
        for url in tag_url:
            res = self.spider_info(url)
            data_list_all.extend(res)
        print(len(data_list_all))  # 250


if __name__ == '__main__':
    spider = SpiderDB()
    spider.main()

标签:__,title,url,text,list,爬虫,案例,div
From: https://www.cnblogs.com/ssrheart/p/18106946

相关文章

  • 爬虫介绍
    Python爬虫(1)介绍Python爬虫是一种自动化获取互联网数据的技术,它通过编写程序实现自动访问网站并抓取所需的数据。爬虫是一种自动化获取互联网数据的技术,通过模拟浏览器行为,向目标网站发送请求并获取响应,然后解析响应中的数据。(2)爬虫的常用库(1)requests用于发送HTTP请......
  • pink前端--小知识点汇总 练手小案例
    一 用子绝夫相定位模式:当鼠标经过时出现遮罩层1.1代码<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><......
  • 【PCB专题】案例:Allegro怎么1:1在纸上打印出PCB板
        首先我们要知道为什么我们需要1:1打印出PCB板?为什么需要1:1打印    一般我们要1:1打印出来这个功能是在新画的器件封装验证、首板结构配合检查、多个板卡互连验证等情况下使用:    在新画了一个器件封装时,如果我们手上有实物,那么通过1:1打印出来后可......
  • 在python中通过面向对象方式,实现烤地瓜案例
    例子:烤地瓜,不同时间,反馈不同状态,并给不同状态地瓜加入不同味道烤地瓜时间0-3分钟,生的4-7分钟,半生不熟的8-12分钟,熟了12分钟以上,已烤熟,糊了用户可以按自己的意思添加调料烤地瓜类:SweetPotato时间:cooktime状态:Cookstate调料:condiments代码实现:classSweetPot......
  • 【Web应用技术基础】JavaScript(1)——案例:猜数字
    因为不能插入视频,所以给大家一张一张截图的点击“重新开始一局游戏” <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0">......
  • Python+selenium+chromedriver实现自动化爬虫(一)安装
    Python+selenium+chromedriver实现自动化爬虫(一)安装一、概述1.python作为程序语言2.selenium作为库函数3.chromedriver.exe作为调用的可执行程序二、安装(一)Python安装(二)selenium安装安装好python后,使用pipinstallselenium安装好selenium库函数,其中pip安装换源及更新......
  • 某宝之店铺id与旺旺号爬虫爬取
    1.先上昨日(24-3-29)图ShopId:旺旺号文章正文:随着互联网的快速发展,大数据时代已经到来。在这个时代,数据成为了宝贵的资源,而如何高效、自动化地获取数据成为了许多企业和开发者关注的焦点。本文将详细介绍如何利用协议爬取、自动化技术与隧道代理相结合,轻松采集淘宝店铺信息......
  • flink水位线案例
    前言:    结合上个水位线知识点做出的题目案例给予以下代码作为参考。例题:1.创建Flink流处理环境。//创建流环境StreamExecutionEnvironmentenv=StreamExecutionEnvironment.getExecutionEnvironment();env.execute();2.从“access.txt”文件中获取数据源。......
  • node.js 入门案例 安装教程
    前言Node.js是一个基于ChromeJavaScript运行时建立的一个平台。Node.js是一个事件驱动I/O服务端JavaScript环境,基于Google的V8引擎,V8引擎执行Javascript的速度非常快,性能非常好。可以让JavaScript在服务器端运行。它具有轻量级、高效、事件驱动、非阻塞I/O等特点,被广泛应......
  • 兼容模式下导致数值类型发生隐式转换,SQL在生产上无法正常使用案例
    兼容模式下导致数值类型发生隐式转换,SQL在生产上无法正常使用案例本文出处:https://www.modb.pro/db/403148基于MogDB版本V2.0.1问题现象厂商研发描述InsertSQL在生产上无法执行,而测试环境中同版本的数据库该SQL可以正常运行。检查SQL后,发现是很简单的insertinto......