做网站建设小程序/杭州制作公司网站

做网站建设小程序,杭州制作公司网站,wordpress sitamap 插件,mac wordpress数据库文件目录 playwright简介使用playwright初窥亚马逊安装playwright打开亚马逊页面 搞数据搜索修改bug数据获取翻页优化结构 简单保存 playwright简介 playwright是微软新出的一个测试工具,与selenium类似,不过与selenium比起来还是有其自身的优势的&#xff…

目录

  • playwright简介
  • 使用playwright初窥亚马逊
    • 安装playwright
    • 打开亚马逊页面
  • 搞数据
    • 搜索
    • 修改bug
    • 数据获取
    • 翻页
      • 优化结构
    • 简单保存

playwright简介

playwright是微软新出的一个测试工具,与selenium类似,不过与selenium比起来还是有其自身的优势的(除了教程少是弱项)。

  • 任何浏览器 • 任何平台 • 一个 API

    • 跨浏览器。 Playwright 支持所有现代渲染引擎,包括 Chromium、WebKit 和 Firefox。
    • 跨平台。 在 Windows、Linux 和 macOS 上进行本地或 CI 测试,无头或有头。
    • 跨语言。 在 TypeScript、JavaScript、Python、.NET、Java 中使用 Playwright API。
    • 测试移动网络。 适用于 Android 的 Google Chrome 和 Mobile Safari 的原生移动模拟。 相同的渲染引擎可以在桌面和云端运行。
      (上面是抄官网的, 下面才是个人的使用体验)
  • 方便

    • 配置方便。与selenium的配置相比较的话,不需要下载额外的驱动,也不需要下载对应版本的浏览器。(就是配置地址不能修改)。
    • 可以异步selenium是只能阻塞式的执行,而playwright可以执行异步。
    • 内存占用少。好像确实是比较少一点。

使用playwright初窥亚马逊

通常情况,每家电商平台都有自己的反爬措施,亚马逊也不例外,所以要尝试一下,当然如果是scrapy这个爬虫框架的话,似乎可以越过反爬措施,内部的逻辑代码是什么没有深究,现在先拿过来用用。

安装playwright

同样的,这个第三方库也要安装,直接使用pip安装就行

pip install playwright

安装完毕之后,还需要安装一些依赖,只要执行一句话即可。这样就能安装了。

playwright install

如果不能安装,或者安装卡进度条了,可以查看这个教程

打开亚马逊页面

小试牛刀一把,看看这个库怎么样

import asyncio
import time
import traceback
from playwright.async_api import async_playwrightclass AmazonBrowser:def __init__(self, headless=True):self.headless = headlessself.browser = Noneself.page = Noneself.playwright = Noneasync def start(self):self.playwright = await async_playwright().start()self.browser = await self.playwright.chromium.launch(headless=False)self.page = await self.browser.new_page()await self.page.goto("https://www.amazon.com/")time.sleep(60)await self.browser.close()if __name__ == "__main__":asyncio.run(AmazonBrowser().start())

在这里插入图片描述
what!!! 不愧是美国注明的电商平台,上来就是验证码=。=还有点不好搞定。

那试试添加headers,应该可以

class AmazonBrowser:def __init__(self, headless=True):self.headless = headlessself.browser = Noneself.page = Noneself.playwright = Noneself.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36","Accept-Language": "en-US,en;q=0.9","Accept-Encoding": "gzip, deflate, br","Referer": "https://www.google.com/", # 伪造,告诉亚马逊网站,说我是从Google搜索页面点击进来的。}

在这里插入图片描述
诶嘿! 来了!

搞数据

在第一个页面里面,没有我们想要的数据,所以我们需要输入内容,然后从新的页面中搞到要的数据。
获取元素 → 搜索 → 搞数据 应该是这个思路。

搜索

我们需要获取2个元素,一个元素是搜索框,另一个元素是搜索按钮(当然搞回车按键也行),从F12里面可以得知,搜索框是下面的内容:
在这里插入图片描述
搜索按钮是下面的:
在这里插入图片描述
先搞定输入框:

import random # 引入random库
class AmazonBrowser:async def start(self):self.playwright = await async_playwright().start()self.browser = await self.playwright.chromium.launch(headless=False)self.page = await self.browser.new_page()await self.page.set_extra_http_headers(self.headers)await self.page.goto("https://www.amazon.com/")search_box = self.page.locator("input#twotabsearchtextbox")# 这里的input有个id,就是twotabsearchtextbox,这个id应该是独立的,所以直接用它。await search_box.wait_for(state="visible")await search_box.type('键盘', delay=random.uniform(50, 200)) time.sleep(60)

【细节讲解】

  • locator:在Playwright中,locator的作用是用于定位页面上的元素,语法有很多:
    • "text=登录"是通过文本匹配,
    • "#username"是通过ID匹配,
    • "//button[@type='submit']"是通过xpath匹配,
    • "a.s-pagination-next.s-pagination-separator"通过css匹配,
    • "a.s-pagination-next.s-pagination-separator:not([aria-disabled="true"])",这个则是排除具有aria-disabled="true"属性的元素。
  • type:在playwright中,type的作用时将文字打入输入框中,与之类似的方法是fill,只不过前者是将文字挨个键入,而后者则是将文字一次性输入,在严格监听页面的网页中,type的的功能用的会比较多,因为可以模拟人的操作,而fill则不行。

再执行看看~
在这里插入图片描述
芜湖~
在这里插入图片描述
同样的,找到搜索按钮并点击就能跳转过去了。

class AmazonBrowser:async def start(self):# ...await search_box.type("键盘", delay=random.uniform(50, 200))await self.page.locator("input#nav-search-submit-button").click()

在这里插入图片描述

修改bug

有的人可能会遇到另外一种情况:
在这里插入图片描述
这个时候搜索输入框和搜索按钮的id就已经不一样了,这种情况的搜索输入框是id="nav-bb-search",搜索按钮是没有id的只有class="nav-bb-button",所以要修改上面的代码

class AmazonBrowser:async def start(self):#...# 同时检测两种搜索框的存在twotab_exists = await self.page.locator("input#twotabsearchtextbox").count()navbb_exists = await self.page.locator("input#nav-bb-search").count()if twotab_exists:search_box = self.page.locator("input#twotabsearchtextbox")search_btn = self.page.locator("input#nav-search-submit-button")elif navbb_exists:search_box = self.page.locator("input#nav-bb-search")search_btn = self.page.locator("input.nav-bb-button")else:raise Exception("No search box found")await search_box.wait_for(state="visible")await search_box.type("键盘", delay=random.uniform(50, 200))await search_btn.click()

数据获取

我们先来看看要搞哪些数据:
在这里插入图片描述
从这个截图上看,有图片,标题,评分,价格。不过有一点是:第二个图片里面有2个价格,到底那个是真实的价格呢?点进去发现,第一个价格是原价,第二个价格好像是二手价格。
在这里插入图片描述
那就弄原价吧,不然太麻烦了。可是他的标题有了,要是标题重复了怎么办?从F12里面可以发现data-asin应该是唯一的,那我们就把这个ASIN弄到手,当然后面也有一个uuid,弄那个也行。
在这里插入图片描述

# 新增依赖库
from urllib.parse import urljoinclass AmazonBrowser:async def start(self):#...await self.page.wait_for_selector('div[role="listitem"][data-asin]', timeout=15000)items = await self.page.locator('div[role="listitem"][data-asin]').all()batch_data = []for index, item in enumerate(items):asin = await item.get_attribute("data-asin")uuid = await item.get_attribute("data-uuid")img = item.locator('img.s-image').firstawait img.scroll_into_view_if_needed()await self.page.wait_for_timeout(500)src = await img.get_attribute('src')href = await item.locator('a.a-link-normal.s-line-clamp-2').get_attribute('href')product = await item.locator('h2.a-size-medium > span').first.inner_text()price_section = item.locator('span.a-price[data-a-color="base"]')if await price_section.count() > 0:price = await price_section.locator('span.a-offscreen').first.inner_text()else:price_section_secondary = item.locator('div.a-row.a-size-base.a-color-secondary')if await price_section_secondary.count() > 0:price = await price_section_secondary.locator('span.a-color-base').first.inner_text()else:price = '暂无价格'batch_data.append({'Product': product,'UUID': uuid,'ASIN': asin,'ImageURL': src,'URL': urljoin(self.target_url, href) if href else None,'Price': price,})

【细节讲解】

  • wait_for_selector:是等待页面上符合选择器的元素出现,最长等待15秒。
    • div[role="listitem"][data-asin]:是选择<div>元素,要求这个元素里面有[role="listitem"]以及[data-asin]这两个东西。
  • await,异步标志,有些情况下需要使用,有些情况下则不需要使用:
    • 需要使用的情况:
      • 涉及网络请求:如 goto()fetch()
      • 获取异步返回的内容:如 text_content()inner_text()
      • 涉及页面交互的操作:如点击、输入、等待
      • 需要时间完成的操作:如 wait_for_selector()
    • 不需要使用的情况:
      • locator()对象
      • 只定义选择器,不交互
      • 直接获取属性,如browser.name

翻页

一页当然是不行的,一页才16条数据,所以肯定要翻页的。同理从F12里面找到翻页标签,那就是
在这里插入图片描述
然后仅有这个也不够,我们还要知道终止,也就是不能点击的情况下,是什么情况的,所以翻到20页得到
在这里插入图片描述
所以需要设计选择器,来判断下一页按钮能不能按下去,或者是能不能检测到终止的<span>

class AmazonBrowser:async def start(self):#...disabled_selector = 'span.s-pagination-next.s-pagination-disabled'enabled_selector = 'a.s-pagination-next:not([aria-disabled="true"])'# 当检测到disable_selector时就继续while True:if await self.page.locator(disabled_selector).count() > 0:breaknext_btn = self.page.locator(enabled_selector)await next_btn.scroll_into_view_if_needed()# 点击前确保元素可交互await next_btn.wait_for(state="visible")await next_btn.click()await self.page.wait_for_timeout(2000)  # 基础等待

在这里插入图片描述

优化结构

但是仅有循环,没有获取数据,这也不是我们想要的,所以接下来是优化结构。将数据获取也翻页分开。

class AmazonBrowser:# ...async def data_collection(self):await self.page.wait_for_selector('div[role="listitem"][data-asin]', timeout=15000)items = await self.page.locator('div[role="listitem"][data-asin]').all()for index, item in enumerate(items):asin = await item.get_attribute("data-asin")uuid = await item.get_attribute("data-uuid")img = item.locator('img.s-image').firstawait img.scroll_into_view_if_needed()await self.page.wait_for_timeout(500)src = await img.get_attribute('src')href = await item.locator('a.a-link-normal.s-line-clamp-2').get_attribute('href')product = await item.locator('h2.a-size-medium > span').first.inner_text()price_section = item.locator('span.a-price[data-a-color="base"]')if await price_section.count() > 0:price = await price_section.locator('span.a-offscreen').first.inner_text()else:price_section_secondary = item.locator('div.a-row.a-size-base.a-color-secondary')if await price_section_secondary.count() > 0:price = await price_section_secondary.locator('span.a-color-base').first.inner_text()else:price = '暂无价格'# self.batch_data要提前声明哦self.batch_data.append({'Product': product,'UUID': uuid,'ASIN': asin,'ImageURL': src,'URL': urljoin(self.target_url, href) if href else None,'Price': price,})async def start(self):#...disabled_selector = 'span.s-pagination-next.s-pagination-disabled'enabled_selector = 'a.s-pagination-next:not([aria-disabled="true"])'# 当检测到disable_selector时就继续while True:if await self.page.locator(disabled_selector).count() > 0:break# 在这里添加await self.data_collection()next_btn = self.page.locator(enabled_selector)await next_btn.scroll_into_view_if_needed()# 点击前确保元素可交互await next_btn.wait_for(state="visible")await next_btn.click()await self.page.wait_for_timeout(2000)  # 基础等待

这样就搞定啦,但是数据要怎么保存呢?可以有两种方式,一种方式是保存在数据库里面,比如mongodb,mysql等等,还可以保存在csv文件里面。

简单保存

在这里就简单的保存成csv文件的样子吧,也就是直接使用pandas保存就行了,下一篇章就搞一下mongodb

# 导入依赖库
import pandas as pd
class AmazonBrowser:def __init__(self):self.df = pd.DataFrame()#... async def start(self):while True:#...while循环内容new_df = pd.DataFrame(self.batch_data)self.df = pd.concat([self.df, new_df], ignore_index=True)self.df.to_csv(path)

就酱~
在这里插入图片描述

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

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

相关文章

Matrix-Breakout-2-Morpheus靶场通关心得:技巧与经验分享

1.安装靶机&#xff0c;并在虚拟机打开&#xff0c;确保和kali在同一个NAT网段 2.使用kali来确定该靶机的IP nmap -O 192.168.139.1/24 3.访问该IP192.168.139.171 4.访问robots.txt 5.扫描目录 gobuster dir -u http://192.168.139.171 -x php,bak,txt,html -w /usr/share/d…

机器学习扫盲系列(2)- 深入浅出“反向传播”-1

系列文章目录 机器学习扫盲系列&#xff08;1&#xff09;- 序 机器学习扫盲系列&#xff08;2&#xff09;- 深入浅出“反向传播”-1 文章目录 前言一、神经网络的本质二、线性问题解析解的不可行性梯度下降与随机梯度下降链式法则 三、非线性问题激活函数 前言 反向传播(Ba…

(一)飞行器的姿态欧拉角, 欧拉旋转, 完全数学推导(基于坐标基的变换矩阵).(偏航角,俯仰角,横滚角)

(这篇写的全是基矢变换矩阵)不是坐标变换矩阵,坐标变换矩阵的话转置一下,之后会有推导. 是通过M转置变换到P撇点.

C语言和C++到底有什么关系?

C 读作“C 加加”&#xff0c;是“C Plus Plus”的简称。 顾名思义&#xff0c;C 就是在 C 语言的基础上增加了新特性&#xff0c;玩出了新花样&#xff0c;所以才说“Plus”&#xff0c;就像 Win11 和 Win10、iPhone 15 和 iPhone 15 Pro 的关系。 C 语言是 1972 年由美国贝…

PCB画图软件PROTEL99SE学习-05画出铜箔来

sch设计的是各个器件的电连接。设计的就是各种节点的网络表关系。不管你器件怎么摆放&#xff0c;好看不好看。都不重要。最终设计电路板是把网络表中连线的网络节点都用铜箔实物相连&#xff0c;让他们导电。 网表导出后我们不用去看他&#xff0c;也不用管他的格式。 我们打开…

helm部署metricbeat

背景 在Elastic Stack 7.5版本之前&#xff0c;系统默认采用内置服务进行监控数据采集&#xff08;称为内部收集机制&#xff09;&#xff0c;这种设计存在显著局限性&#xff1a; 当ES集群崩溃时自带的节点监控也会随之崩溃&#xff0c;直到集群恢复前&#xff0c;崩溃期间的…

【菜鸟飞】AI多模态:vsCode下python访问阿里云通义文生图API

目标 有很多多模态的AI工具&#xff0c;用的少就用在线图形化的&#xff0c;需要批量&#xff0c;就尝试代码生成&#xff0c;本文尝试代码调用多模态AI&#xff0c;阿里通义有免费额度&#xff0c;作为练手应该挺好&#xff0c;如果以后选其他的&#xff0c;技术也是相通的。…

从零实现本地文生图部署(Stable Diffusion)

1. 依赖安装 文件打包下载地址&#xff08;Stable Diffusion&#xff09; # git &#xff1a; 用于下载源码 https://git-scm.com/downloads/win # Python 作为基础编译环境 https://www.python.org/downloads/ # Nvidia 驱动&#xff0c;用于编译使用GPU显卡硬件 https://ww…

缓存监控治理在游戏业务的实践和探索

作者&#xff1a;来自 vivo 互联网服务器团队- Wang Zhi 通过对 Redis 和 Caffeine 的缓存监控快速发现和定位问题降低故障的影响面。 一、缓存监控的背景 游戏业务中存在大量的高频请求尤其是对热门游戏而言&#xff0c;而应对高并发场景缓存是一个常见且有效的手段。 游戏业…

WordPress漏洞

一&#xff0c;后台修改模板拿WebShell 1&#xff0c;安装好靶场后访问 2&#xff0c;在如图所示的位置选择一个php文件写入一句话木马&#xff0c;我们这里选择在404.php中写入 3&#xff0c;访问404.php 二&#xff0c;上传主题拿WebShell 1&#xff0c;找到如图所示的页面…

【Linux系列】实时监控磁盘空间:`watch -n 1 ‘df -h‘` 命令详解

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

腾讯云大模型知识引擎×DeepSeek:股票分析低代码应用实践

项目背景与发展历程 在金融科技快速发展的今天&#xff0c;股票分析作为投资决策的核心环节&#xff0c;正面临数据量激增和复杂性提升的挑战。传统股票分析依赖人工处理&#xff0c;效率低下且成本高昂&#xff0c;而人工智能&#xff08;AI&#xff09;的引入为这一领域带来…

高性能边缘计算网关-高算力web组态PLC网关

高性能EG8200Pro边缘计算算力网关-超强处理能力 样机申请测试&#xff1a;免费测试超30天&#xff08;https://www.iotrouter.com/prototype/&#xff09; 产品主要特点和特色功能 设备概览与连接能力 设备型号&#xff1a;EG8200P。主要特点&#xff1a; 支持多种工业协议&am…

Web开发-JS应用原生代码前端数据加密CryptoJS库jsencrypt库代码混淆

知识点&#xff1a; 1、安全开发-原生JS-数据加密&代码混淆 2、安全开发-原生JS-数据解密安全案例 一、演示案例-WEB开发-原生JS&第三方库-数据加密 前端技术JS实现&#xff1a; 1、非加密数据大致流程&#xff1a; 客户端发送->明文数据传输-服务端接受数据->…

【Dive Into Stable Diffusion v3.5】1:开源项目正式发布——深入探索SDv3.5模型全参/LoRA/RLHF训练

目录 1 引言2 项目简介3 快速上手3.1 下载代码3.2 环境配置3.3 项目结构3.4 下载模型与数据集3.5 运行指令3.6 核心参数说明3.6.1 通用参数3.6.2 优化器/学习率3.6.3 数据相关 4 结语 1 引言 在人工智能和机器学习领域&#xff0c;生成模型的应用越来越广泛。Stable Diffusion…

Docker Compose部署MantisBT

文章目录 1.docker-compose-mantisbt.yml2.部署3.配置MantisBT4.登录5.修改配置5.1 取消修改用户需要邮箱确认 1.docker-compose-mantisbt.yml version: "3" services:web:image: okainov/mantisbt:latestcontainer_name: mantisbt_webports:- "8989:80"e…

Grokking System Design 系统设计面试问题

《Grokking the System Design Interview》列举了多个经典的系统设计题目,通常按照 不同的业务场景和技术难点 进行分类。以下是一些常见的分类和题目示例: 1. 社交网络类 设计 Twitter(支持关注/取关、推文、Feed 流) 设计 Facebook Messenger(即时聊天,支持在线/离线状…

## DeepSeek写射击手机小游戏

DeepSeek写射击手机小游戏 提问 根据提的要求&#xff0c;让DeepSeek整理的需求&#xff0c;进行提问&#xff0c;内容如下&#xff1a; 请生成一个包含以下功能的可运行移动端射击小游戏H5文件&#xff1a; 要求 可以重新开始游戏 可以暂停游戏 射击位置在底部中间&#xff…

【智能体】| 知识库、RAG概念区分以及智能体是什么

文章目录 前言简介大模型“幻觉”问题如何解决“幻觉”问题&#xff1f; RAG、智能体、RAG智能体概念什么是检索增强型生成&#xff08;RAG&#xff09;模拟简单的RAG场景 AI系统中的智能体是什么什么是Agentic RAG&#xff1f;Agentic RAG如何工作&#xff1f;Agentic RAG架构…

Linux与HTTP中的Cookie和Session

HTTP中的Cookie和Session 本篇介绍 前面几篇已经基本介绍了HTTP协议的大部分内容&#xff0c;但是前面提到了一点「HTTP是无连接、无状态的协议」&#xff0c;那么到底有什么无连接以及什么是无状态。基于这两个问题&#xff0c;随后解释什么是Cookie和Session&#xff0c;以…