【XMU学科实践二】豆瓣爬虫实践

文章目录

叠甲:仅供学习。。

XMU的小朋友实在不会了可以参考我的思路,但还是建议自己敲一遍哈。

学科实践二还是挺有意思的!

分析豆瓣阅读网站

豆瓣阅读出版页面

打开浏览器开发者工具,可以看到如下图所示的内容

完整爬虫代码

我23年3月的时候,是把豆瓣全部爬取了()一共5w6k条

python 复制代码
import sys
import numpy as np
sys.path.append('/home/aistudio/external-libraries')
import json
import re
import requests
import pandas as pd
import datetime
from bs4 import BeautifulSoup
import base64
import os
import random
import time
#代理池
proxy_list = [
    '127.0.0.1:15732',   #自己的代理服务器地址
    '192.168.56.1.15732'  
]
proxy = random.choice(proxy_list)
proxies = {
'http':  proxy,
'https':  proxy,
}
user_agents = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
                   'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
                   'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2',
                   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
                   'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
                   'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0'
                   ]
headers = { 
       'User-Agent': random.choice(user_agents),
}
url='https://read.douban.com/provider/all'                     
cookie={'cookie':'bid=kRRUP5Adrsc; _ga=GA1.3.1583431493.1679359048; _gid=GA1.3.240421151.1679359048; _ga=GA1.1.1583431493.1679359048; page_style="mobile"; dbcl2="215291240:+lGgZ069L0g"; _pk_ses.100001.a7dd=*; ck=AT7V; _ga_RXNMP372GL=GS1.1.1679406549.4.1.1679408190.60.0.0; _pk_id.100001.a7dd=0f38c905a23f4f70.1679359049.4.1679408190.1679402067.; _gat=1'}
try:
    response = requests.get(url,headers=headers,cookies=cookie,proxies=proxies)
    #将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
    soup = BeautifulSoup(response.text,'lxml')  
    
    #返回所有的<div>所有标签
    publishes = soup.find_all('div',{'class':'provider-group'})
    pbs=[]
    item_list=[]
    #print(publishes)
    #enumerate爬虫中的遍历
    #遍历所有出版社
    #pb为当前出版社
    for index,pb in enumerate(publishes):
        #if (index<=1):
        if True:
            pb_list={}
            pb_list['item_name']=pb.find_next('div').text
            p=pb.find_next('ul')
            li_s=p.find_all('li')#li_s存储了当前出版社的所有数据。
            
        #print(li_s)
        for li in li_s:
            item_li={}
            #item_li为进入当前出版社内页书单的链接
            item_li['href']='https://read.douban.com'+li.find_next('a').get('href')

            url2=item_li['href']
            response2=requests.get(url2,headers=headers,cookies=cookie,proxies=proxies)
            soup2 = BeautifulSoup(response2.text,'lxml')  
            
            #遍历当前出版社的所有书单页面
            while soup2.find('li',class_='next')!=None:
                #booklist为当前页面的所有<div class=info>的书籍数据
                booklist=soup2.find_all('div',{'class':'info'})
                #print(booklist)
                #print(publishes2)
                #遍历当前页面的所有书籍
                #book为当前的书籍数据
                for book in booklist:
                    
                    if(book.find('h4',class_='title')==None):
                        continue
                    title =book.find('h4',class_='title').text
                    item_li['name']=title
                    if(book.find('div',class_='sales-price')!=None):
                        price=book.find('div',class_='sales-price').text
                        item_li['price']=price
                    elif(book.find('span',class_='discount-price')!=None):
                        price=book.find('span',class_='discount-price').text
                        item_li['price']=price
                    elif(book.find('span',class_='price-tag')!=None):
                        price=book.find('span',class_='price-tag').text
                        item_li['price']=price
                    else:
                        continue
                    #输出查看
                    print(f"《{title}》:{price}")#1000行截断,保存成xlsx比较好
                    #item_list用来存储要求得的书名和价格的list型数据结构,一维
                    item_list.append([title,price])
                    t = random.random() #随机大于0 且小于1 之间的小数
                    time.sleep(t)
                    
                temp2=soup2.find('li',class_='next')
                #若存在后页
                if temp2.find('a')!=None:
                    #跳转到下一页
                    url3=url2+temp2.find('a').get('href')
                    response2=requests.get(url3,headers=headers,cookies=cookie,proxies=proxies)
                    soup2 = BeautifulSoup(response2.text,'lxml') 
                else:
                    break    
    df=pd.DataFrame(item_list)
    df.columns=['书籍名称','价格']
    print(df)
    #保存到excel文件中
    df.to_excel("爬虫数据.xlsx")
except Exception as e:
    print(e)
相关推荐
愚公搬代码17 小时前
【愚公系列】《Python网络爬虫从入门到精通》045-Charles的SSL证书的安装
网络·爬虫·python·网络协议·ssl
cliff,18 小时前
【python爬虫】酷狗音乐爬取
笔记·爬虫·python·学习
数据小小爬虫1 天前
利用PHP爬虫获取17网(17zwd)商品详情:实战指南
开发语言·爬虫·php
猿小猴子1 天前
Python3 爬虫 爬虫中间件
爬虫·中间件
q567315231 天前
使用Lua和lua-resty-http-simple库的爬虫程序爬取图片
爬虫·http·lua
SRC_BLUE_171 天前
[网络爬虫] 动态网页抓取 — Selenium 介绍 & 环境配置
网络·爬虫·selenium·测试工具
B站计算机毕业设计超人1 天前
计算机毕业设计Python+DeepSeek-R1大模型微博舆情分析系统 微博舆情预测 微博爬虫 微博大数 据(源码+LW文档+PPT+详细讲解)
爬虫·python·学习·算法·机器学习·毕业设计·数据可视化
朱剑君2 天前
番外篇 - Docker的使用
爬虫·docker·容器
九丶黎2 天前
爬虫案例七Python协程爬取视频
爬虫·python·音视频
HerrFu2 天前
可狱可囚的爬虫系列课程 19:静态页面和动态页面之分
爬虫·python