Python读取阿里法拍网的html+解决登录cookie

news2025/6/9 0:56:09

 效果图

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from lxml import etree

def get_taobao_auction_data():
    # 配置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument('--headless')  # 无头模式
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_argument('--disable-extensions')
    chrome_options.add_argument('--ignore-certificate-errors')
    chrome_options.add_argument('--window-size=1920,1080')
    
    # 设置Chrome浏览器路径
    chrome_options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    
    # 设置User-Agent
    chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
    
    try:
        print("正在初始化Chrome驱动...")
        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=chrome_options)
        print("Chrome驱动初始化成功")
        
        # 设置页面加载超时时间
        driver.set_page_load_timeout(30)
        
        # 访问目标网页
        url = "https://zc-paimai.taobao.com/wow/pm/default/pc/zichansearch?fcatV4Ids=[%22206067201%22]&corp_type=[%226%22]&structFieldMap={%22corp_type%22:[%226%22]}&page=1"
        driver.get(url)
        
        # 等待页面加载
        print("等待页面加载...")
        time.sleep(10)
        
        # 执行JavaScript滚动页面
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(2)
        
        # 获取页面内容
        page_source = driver.page_source
        
        # 保存原始响应到文件
        with open('taobao_auction.html', 'w', encoding='utf-8') as f:
            f.write(page_source)
        print("页面内容已保存到 taobao_auction.html")
        
        # 使用lxml解析HTML
        html = etree.HTML(page_source)
        
        # 解析拍卖项目 - 更新XPath以匹配实际结构
        items = html.xpath('//div[contains(@style, "border: 1px solid rgb(230, 230, 230)")]')
        
        if items:
            print(f"\n找到 {len(items)} 个拍卖项目")
            
            for item in items:
                try:
                    # 提取详情链接
                    detail_url = item.xpath('.//a/@href')
                    detail_url = "https:" + detail_url[0] if detail_url else "无链接"
                    
                    # 提取图片URL
                    img_url = item.xpath('.//img[contains(@style, "object-fit: cover")]/@src')
                    img_url = "https:" + img_url[0] if img_url else "无图片"
                    
                    # 提取标题
                    title = item.xpath('.//span[contains(@class, "text") and contains(@style, "font-size: 16px")]/@title')
                    title = title[0].strip() if title else "无标题"
                    
                    # 提取当前价格
                    current_price = item.xpath('.//div[contains(text(), "当前价")]/following-sibling::div//span[contains(@style, "font-size: 24px")]/text()')
                    current_price = current_price[0].strip() if current_price else "无价格"
                    
                    # 提取评估价
                    eval_price = item.xpath('.//div[contains(text(), "评估价")]/following-sibling::span[2]/text()')
                    eval_price = eval_price[0].strip() if eval_price else "无评估价"
                    
                    # 提取拍卖状态
                    status = item.xpath('.//div[contains(@style, "background: rgb(235, 0, 69)")]/text()')
                    status = status[0].strip() if status else "无状态"
                    
                    # 提取围观次数
                    views = item.xpath('.//span[contains(text(), "次围观")]/preceding-sibling::span/text()')
                    views = views[0].strip() if views else "0"
                    
                    # 提取报名人数
                    signups = item.xpath('.//span[contains(text(), "人报名")]/preceding-sibling::span/text()')
                    signups = signups[0].strip() if signups else "0"
                    
                    print("\n拍卖项目信息:")
                    print(f"标题: {title}")
                    print(f"当前价: {current_price}")
                    print(f"评估价: {eval_price}")
                    print(f"状态: {status}")
                    print(f"围观次数: {views}")
                    print(f"报名人数: {signups}")
                    print(f"图片URL: {img_url}")
                    print(f"详情链接: {detail_url}")
                    print("-" * 50)
                    
                except Exception as e:
                    print(f"解析项目时出错: {e}")
                    continue
        else:
            print("未找到拍卖项目,请检查页面结构")
            print("请查看保存的HTML文件以分析页面结构")
            
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        # 关闭浏览器
        try:
            driver.quit()
        except:
            pass

if __name__ == "__main__":
    get_taobao_auction_data()

获取登录cookie

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from lxml import etree
import re

def get_auction_detail():
    # 1. 采集页面并保存html(如已有可跳过)
    chrome_options = Options()
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_argument('--disable-extensions')
    chrome_options.add_argument('--ignore-certificate-errors')
    chrome_options.add_argument('--window-size=1920,1080')
    chrome_options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')

    try:
        print("正在初始化Chrome驱动...")
        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=chrome_options)
        print("Chrome驱动初始化成功")
        driver.set_page_load_timeout(30)
        print("访问淘宝首页...")
        driver.get("https://www.taobao.com")
        time.sleep(3)
        print("请在浏览器中手动登录淘宝...")
        input("登录完成后请按回车键继续...")
        cookies = driver.get_cookies()
        print("已获取登录Cookie")
        url = "https://sf-item.taobao.com/sf_item/903309584546.htm"
        print(f"正在访问拍卖详情页: {url}")
        driver.get(url)
        print("等待页面加载...")
        time.sleep(10)
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(2)
        page_source = driver.page_source
        with open('auction_detail.html', 'w', encoding='utf-8') as f:
            f.write(page_source)
        print("页面内容已保存到 auction_detail.html")
    except Exception as e:
        print(f"采集页面时发生错误: {e}")
    finally:
        try:
            driver.quit()
        except:
            pass

    # 2. 解析本地auction_detail.html,提取全部关键信息
    print("\n正在解析 auction_detail.html ...")
    with open('auction_detail.html', 'r', encoding='utf-8') as f:
        html = etree.HTML(f.read())

    def get_first(xpath_expr):
        res = html.xpath(xpath_expr)
        return res[0].strip() if res else ''

    # 标题
    title = get_first('//title/text()')

    # 当前价
    current_price = get_first('//span[contains(@class,"pm-current-price")]/em/text()')
    if not current_price:
        current_price = get_first('//span[contains(@class,"J_Price")]/em/text()')

    # 变卖价、保证金、加价幅度、评估价、变卖周期、延时周期、竞价规则(表格)
    def get_table_value(key):
        td = html.xpath(f'//table//span[contains(text(),"{key}")]/../../following-sibling::td[1]//span[contains(@class,"family-tahoma")]/text()')
        if not td:
            # 兼容" : "后直接文本
            td = html.xpath(f'//table//span[contains(text(),"{key}")]/../following-sibling::div//span[contains(@class,"family-tahoma")]/text()')
        if not td:
            # 兼容" : "后直接文本(无span)
            td = html.xpath(f'//table//span[contains(text(),"{key}")]/../../following-sibling::td[1]//text()')
        return td[0].strip() if td else ''

    sell_price = get_table_value('变卖价')
    deposit = get_table_value('保证金')
    increase = get_table_value('加价幅度')
    eval_price = get_table_value('评估价')
    sell_period = get_table_value('变卖周期')
    delay_period = get_table_value('延时周期')
    rule = ''
    rule_td = html.xpath('//table//span[contains(text(),"竞价规则")]/../../following-sibling::td[1]//span/text()')
    if rule_td:
        rule = rule_td[0].strip()
    else:
        # 兼容" : "后直接文本
        rule = get_first('//table//span[contains(text(),"竞价规则")]/../following-sibling::div//span/text()')

    # 主办法院
    court = get_first('//div[@class="unit-org-content"]/p/text()')
    # 拍卖公司及联系人
    company = get_first('//em[contains(@class,"contact-unit-person")]/text()')
    # 联系方式(手机号)
    phone = get_first('//span[@class="c-title" and contains(text(),"手机")]/following-sibling::span[@class="c-text"]/text()')
    # 公告链接
    notice_link = html.xpath('//a[contains(@class,"view-ano")]/@href')
    notice_link = notice_link[0] if notice_link else ''
    if notice_link and not notice_link.startswith('http'):
        notice_link = 'https:' + notice_link

    print("\n拍卖详情信息:")
    print(f"标题: {title}")
    print(f"当前价: {current_price}")
    print(f"变卖价: {sell_price}")
    print(f"保证金: {deposit}")
    print(f"加价幅度: {increase}")
    print(f"评估价: {eval_price}")
    print(f"变卖周期: {sell_period}")
    print(f"延时周期: {delay_period}")
    print(f"竞价规则: {rule}")
    print(f"主办法院: {court}")
    print(f"拍卖公司及联系人: {company}")
    print(f"联系方式: {phone}")
    print(f"公告链接: {notice_link}")
    print("-" * 50)

if __name__ == "__main__":
    get_auction_detail() 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2404776.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

electron-vite串口通信

一、构建项目后,安装“串口通信库” npm install serialport二、设置 npm install --save-dev electron-rebuild ./node_modules/.bin/electron-rebuild 注意:如果执行报错以下问题 1、未配置python变量 2、没有Microsoft Visual Studio BuildTools 3…

中山大学美团港科大提出首个音频驱动多人对话视频生成MultiTalk,输入一个音频和提示,即可生成对应唇部、音频交互视频。

由中山大学、美团、香港科技大学联合提出的MultiTalk是一个用于音频驱动的多人对话视频生成的新框架。给定一个多流音频输入和一个提示,MultiTalk 会生成一个包含提示所对应的交互的视频,其唇部动作与音频保持一致。 相关链接 论文:https://a…

redis分片集群架构

主从集群解决高并发,哨兵解决高可用问题。但是任然有两个问题没有解决:1海量数据存储问题;2高并发写的问题(如果服务中有大量写的请求) 那就可以采用分片集群架构解决这些问题 分片集群特征 分片集群中有多个master…

关于物联网的基础知识(一)

成长路上不孤单😊😊😊😊😊😊 【14后😊///计算机爱好者😊///持续分享所学😊///如有需要欢迎收藏转发///😊】 今日分享关于物联网的基础知识(一&a…

电脑商城--用户注册登录

用户注册 1 用户-创建数据表 1.使用use命令先选中store数据库。 USE store; 2.在store数据库中创建t_user用户数据表。 CREATE TABLE t_user (uid INT AUTO_INCREMENT COMMENT 用户id,username VARCHAR(20) NOT NULL UNIQUE COMMENT 用户名,password CHAR(32) NOT NULL COMME…

什么是梯度磁场

梯度磁场是叠加在均匀主磁场(如MRI中的静磁场B₀)上的一种特殊磁场,其强度会沿着特定方向(如X、Y或Z轴)呈线性变化。这种磁场在磁共振成像和粒子控制等领域发挥着关键作用,主要用于实现空间位置的精确编码和…

从零开始的python学习(七)P102+P103+P104+P105+P106+P107

本文章记录观看B站python教程学习笔记和实践感悟,视频链接:【花了2万多买的Python教程全套,现在分享给大家,入门到精通(Python全栈开发教程)】 https://www.bilibili.com/video/BV1wD4y1o7AS/?p6&share_sourcecopy_web&v…

Linux--进程的调度

1.进程切换 CPU上下⽂切换:其实际含义是任务切换, 或者CPU寄存器切换。当多任务内核决定运⾏另外的任务时, 它保存正在运⾏任务的当前状态, 也就是CPU寄存器中的全部内容。这些内容被保存在任务⾃⼰的堆栈中, ⼊栈⼯作完成后就把下⼀个将要运⾏的任务的当前状况从该…

VmWare Ubuntu22.04 搭建DPDK 20.11.1

一、开发环境 Ubuntu 版本 二、增加虚拟机的网卡 给虚拟机增加1个网卡,加上原来的网卡,一共2个 网络适配器作为 ssh 连接的网卡,网络适配器2作为 DPDK 运行的网卡。 三、NAT模式简介 这里待补充,网上都是那一张图,看不懂 四、使网卡名称从0开始命名 进入管理员权限 s…

selenium-自动更新谷歌浏览器驱动

1、简介 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题,因为有些网页数据是通过JavaScript动态加载的。selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如输入…

Docker容器部署elasticsearch8.*与Kibana8.*版本使用filebeat采集日志

第 1 步:使用 Docker Compose 部署 Elasticsearch 和 Kibana 首先,我们需要创建一个 docker-compose.yml 文件来定义和运行 Elasticsearch 和 Kibana 服务。这种方式可以轻松管理两个容器的配置和网络。 创建 docker-compose.yml 文件 在一个新的文件夹…

OpenCV CUDA模块图像处理------双边滤波的GPU版本函数bilateralFilter()

操作系统:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 编程语言:C11 算法描述 该函数在 GPU 上执行双边滤波操作,是一种非线性平滑滤波器,能够在 保留边缘的同时去除噪声。 函数原型 void cv::cuda:…

华为手机开机卡在Huawei界面不动怎么办?

遇到华为手机卡在启动界面(如HUAWEI Logo界面)的情况,可依次尝试以下解决方案,按操作复杂度和风险由低到高排序: 🔧 一、强制重启(优先尝试) 1.通用方法‌ 长按 ‌电源键 音量下键‌…

go语言map扩容

map是什么? ​在Go语言中,map是一种内置的无序key/value键值对的集合,可以根据key在O(1)的时间复杂度内取到value,有点类似于数组或者切片结构,可以把数组看作是一种特殊的map,数组的key为数组的下标&…

5.3 Spring Boot整合JPA

本文详细介绍了如何在Spring Boot项目中整合Spring JPA,实现对数据库的高效操作。首先,创建Spring Boot项目并添加必要的依赖,如Druid数据源。接着,配置数据源属性,创建实体类Comment和Article,并使用JPA注…

腾讯开源视频生成工具 HunyuanVideo-Avatar,上传一张图+一段音频,就能让图中的人物、动物甚至虚拟角色“活”过来,开口说话、唱歌、演相声!

腾讯混元团队提出的 HunyuanVideo-Avatar 是一个基于多模态扩散变换器(MM-DiT)的模型,能够生成动态、情绪可控和多角色对话视频。支持仅 10GB VRAM 的单 GPU运行,支持多种下游任务和应用。例如生成会说话的虚拟形象视频&#xff0…

[文献阅读] Emo-VITS - An Emotion Speech Synthesis Method Based on VITS

[文献阅读]:An Emotion Speech Synthesis Method Based on VITS 在VITS基础上通过参考音频机制,获取情感信息,从而实现的情感TTS方式。 摘要 VITS是一种基于变分自编码器(VAE)和对抗神经网络(GAN&#xf…

OpenCV-Python Tutorial : A Candy from Official Main Page(持续更新)

OpenCV-Python 是计算机视觉领域最流行的开源库之一,它结合了 OpenCV (Open Source Computer Vision Library) 的 C 高性能实现和 Python 的简洁易用特性,为开发者提供了强大的图像和视频处理能力。具有以下优势: 典型应用领域: …

【Vue】指令补充+样式绑定+计算属性+侦听器

【指令补充】 【指令修饰符】 指令修饰符可以让指令的 功能更强大,书写更便捷 分类: 1.按键修饰符(侦测当前点击的是哪个按键) 2.事件修饰符(简化程序对于阻止冒泡, 一些标签的默认默认行为的操作&…

LLM 笔记:Speculative Decoding 投机采样

1 基本介绍 投机采样(Speculative Sampling)是一种并行预测多个可能输出,然后快速验证并采纳正确部分的加速策略 在不牺牲输出质量的前提下,减少语言模型生成 token 所需的时间 传统的语言模型生成是 串行 的 必须生成一个&…