爬虫日常练习

1.爬取电子出版社的生活类书本数据

通过ajax查找实现

python 复制代码
# -- coding: utf-8 --
# 目标:生活板块的书籍书名、价格和作者
import json
import jsonpath
import requests


headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
           'cookie':'acw_tc1a0c639f17292171657431353e00d3333404ced367ab5ea36be81ca90c3609;JSESSIONID=A8143E0428FC4DA3171E8560C47966E8'}

# response = requests.get('https://www.ptpress.com.cn/recommendBook/getRecommendBookListForPortal?bookTagId=d5cbb56d-09ef-41f5-9110-ced741048f5f',headers=headers)
# dict_data = json.loads(response.content)
# print(jsonpath.jsonpath(dict_data,'$..bookName'))

2.爬取详细信息

python 复制代码
# 目标:书籍书名、价格和作者
# 1.获取书名id的ajax
# 2.根据id获取单本书籍信息的ajax
# 3.根据data得到想要的内容
import requests  # 导入请求库,用于发送 HTTP 请求
import json  # 导入 JSON 库,用于处理 JSON 数据

# 定义获取推荐书籍列表的 URL
url = 'https://www.ptpress.com.cn/recommendBook/getRecommendBookListForPortal?bookTagId=d5cbb56d-09ef-41f5-9110-ced741048f5f'

# 设置请求头,模拟浏览器请求
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
    'cookie': 'acw_tc1a0c639f17292171657431353e00d3333404ced367ab5ea36be81ca90c3609; JSESSIONID=A8143E0428FC4DA3171E8560C47966E8'
}

# 发送 GET 请求以获取推荐书籍列表
response = requests.get(url=url, headers=headers)
books = response.json()['data']

def output_to_console(books):
    # 输出标题
    print('书名\t作者\t价格')

    # 遍历返回的数据中的每本书
    for book in books:
        book_id = book['bookId']
        detail = get_book_details(book_id)  # 获取书籍详细信息
        if detail:
            # 提取书名、作者和折后价格
            book_name = detail['bookName']
            author = detail['author']
            discount_price = detail['discountPrice']
            print(f"{book_name}\t{author}\t{discount_price}")

def get_book_details(book_id):
    url = 'https://www.ptpress.com.cn/bookinfo/getBookDetailsById'
    params = {'bookId': book_id}
    response = requests.post(url=url, headers=headers, params=params)
    return response.json()['data'] if response.json().get('success') else None

# 调用函数输出书籍信息
output_to_console(books)

3.爬取当当网书本信息(静态网页练习)

python 复制代码
# -- coding: utf-8 --
# 爬取目标:排名、书名、图片地址、作者、推荐指数、五星评分次数、价格
import requests
import time
from lxml import etree

headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
           'cookie':'ddscreen=2; dest_area=country_id%3D9000%26province_id%3D111%26city_id%20%3D0%26district_id%3D0%26town_id%3D0; __permanent_id=20241017154613694111150420084440082; __visit_id=20241017154613696429022245816885774; __out_refer=; __trace_id=20241017154613696426813165695783602'}

response = requests.get('http://bang.dangdang.com/books/fivestars/01.00.00.00.00.00-recent30-0-0-1-1',headers=headers)
num=1
while num<10:
    url = 'http://bang.dangdang.com/books/fivestars/01.00.00.00.00.00-recent30-0-0-1-'+str(num)
    response  = requests.get(url,headers=headers)
    # print(response.status_code)
    # print(response.text)
    time.sleep(3)
    html = etree.HTML(response.text)

    # el_list = html.xpath('/html/body/div[3]/div[3]/div[2]/ul/li') # 已经确定访问成功且能读取数据,静态网页换xpath定位方法
    el_list = html.xpath('//ul[@class="bang_list clearfix bang_list_mode"]/li')
    print(len(el_list))

    for li in el_list:
        paiming = li.xpath('./div[1]/text()')
        shuming = li.xpath('./div[3]/a/@title')
        tupiandizhi = li.xpath('./div[2]/a/img/@src')
        zuozhe = li.xpath('./div[5]/a/text()') if len(li.xpath('./div[5]/a/text()')) > 0 else "未知"
        tuijian = li.xpath('./div[4]/span[2]/text()')
        cishu = li.xpath('./div[7]/span/text()')
        jiage = li.xpath('./div[8]/p[1]/span[1]/text()')

        dict = {
            '排名': paiming,
            '书名': shuming,
            '图片地址': tupiandizhi,
            '作者': zuozhe,
            '推荐指数': tuijian,
            '五星评分次数': cishu,
            '价格': jiage
        }
        print(dict)

    num+=1
相关推荐
喵手7 小时前
Python爬虫实战:HTTP缓存系统深度实战 — ETag、Last-Modified与requests-cache完全指南(附SQLite持久化存储)!
爬虫·python·爬虫实战·http缓存·etag·零基础python爬虫教学·requests-cache
喵手7 小时前
Python爬虫实战:容器化与定时调度实战 - Docker + Cron + 日志轮转 + 失败重试完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·容器化·零基础python爬虫教学·csv导出·定时调度
喵手9 小时前
Python爬虫实战:全站 Sitemap 自动发现 - 解析 sitemap.xml → 自动生成抓取队列的工业级实现!
爬虫·python·爬虫实战·零基础python爬虫教学·sitemap·解析sitemap.xml·自动生成抓取队列实现
iFeng的小屋10 小时前
【2026年新版】Python根据小红书关键词爬取所有笔记数据
笔记·爬虫·python
Love Song残响10 小时前
揭秘Libvio爬虫:动态接口与逆向实战
爬虫
喵手12 小时前
Python爬虫实战:构建招聘会数据采集系统 - requests+lxml 实战企业名单爬取与智能分析!
爬虫·python·爬虫实战·requests·lxml·零基础python爬虫教学·招聘会数据采集
iFeng的小屋13 小时前
【2026最新当当网爬虫分享】用Python爬取千本日本相关图书,自动分析价格分布!
开发语言·爬虫·python
数研小生14 小时前
关键词搜索京东列表API技术对接指南
大数据·数据库·爬虫
喵手14 小时前
Python爬虫实战:网页截图归档完全指南 - 构建生产级页面存证与历史回溯系统!
爬虫·python·爬虫实战·零基础python爬虫教学·网页截图归档·历史回溯·生产级方案
Blurpath住宅代理14 小时前
动态代理的五大优点:提升爬虫效率与安全性
网络·爬虫·动态ip·住宅ip·住宅代理