前言

最近因为项目需要又得抓一批数据,和之前的scrapy不同,这次选择使用selenium来爬取。两种方法的区别如下:

  • scrapy之类的库是基于网络请求来爬取的,也就是直接向目标服务器发送http请求,在这个过程中需要自己构造请求字段也就是json格式的request body。
  • selenium一类的库是基于自动化测试的,我们只需要知道想要访问的链接就好,其它的(异步加载图片、信息之类的)交给浏览器来做。也因此在使用时需要额外下载浏览器以及对应驱动,比如googledriver。

总而言之,虽然selenium在速度上是远远不如直接发请求的scrapy一类的库的,但可以完美地规避反爬策略,因为自动化测试相当于是模拟人去访问一个网站,因此还可以进行网页自动截图之类的操作,可以说是非常简单方便。

安装

  1. 下载selenium库:pip install selenium
  2. 下载浏览器驱动:一般来说就是ChromeDriver,先看自己电脑上的Chrome版本,然后在给出的链接中下载对应版本的ChromeDriver。
  3. 将ChromeDriver加到环境变量里,方法就不多说了,网上随便找找就有,可以参考[windows环境变量配置/linux、mac环境变量配置]

对网页进行滚动截屏

首先是一个比较简单的应用,就是对整个网页进行截屏,并且在网页长度超出窗口长度时可以滚动截屏并自动拼接。主要思想是获取网页长度page_height与窗口长度window_height,然后循环定位到网页的不同位置来截图,并把截图都拼接到一起。话不多说直接上代码:

from io import BytesIO
import traceback
from time import sleep
from PIL import Image
import numpy as np
from selenium import webdriverdef url_screenshot(ad_url, index):try:chrome_options = webdriver.ChromeOptions()chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])chrome_options.add_argument('--headless')  # 后台静默运行driver = webdriver.Chrome(options=chrome_options)driver.get(ad_url)driver.fullscreen_window()  # 全屏窗口# 当前窗口的高度window_height = driver.get_window_size()['height']  # 页面高度page_height = driver.execute_script('return document.documentElement.scrollHeight')  print('window_height:{},page_height:{}'.format(window_height,page_height)img_binary = driver.get_screenshot_as_png()base_img = np.array(Image.open(BytesIO(img_binary)))if page_height > window_height:n = page_height // window_height  # 需要滚动的次数for i in range(n):driver.execute_script(f'document.documentElement.scrollTop={window_height*(i+1)};')sleep(5)img = np.array(Image.open(BytesIO(driver.get_screenshot_as_png())))if i==n-1:out = window_height * (i + 1) - (page_height - window_height)img = img[2*out:]base_img = np.append(base_img, img, axis=0)  # 拼接图片driver.quit()Image.fromarray(base_img).save("{}.png".format(index)) # 保存图片except:traceback.print_exc()if __name__ == '__main__':with open('url_list','r') as fp:    # 把待截图的网页链接写在一个文件里,每行一个链接lines = fp.readlines()index = 0for line in lines:index+=1url_screenshot(line.strip(),index)print('get url:{}'.format(line))

获取淘宝商品数据

接下来一个稍微复杂一点的例子,通过关键词搜索来爬取淘宝商品的图片。
流程是:

  • run、getPage:通过关键词构造商品查询链接,并访问。
  • getItem:针对查询结果,获取每个商品详情页的链接并访问,同时翻页。
  • getItemDetail:获取商品详细信息,这里只获取了商品中包含的图片信息,想要其他信息可以在此构造别的xpath解析路径来获取。

整个过程没什么难点,主要就是分析获取的html界面,然后解析里面的元素结构,编写xpath来获取里面的某个元素。可以参考之前的关于scrapy的博客:https://blog.csdn.net/qq_34392457/article/details/117029090,这里对于如何分析一个网页的html写得更详细。

import cv2
import numpy as np
from lxml import etree
from selenium import webdriver
import time
import requests
import os
import shutilclass Crawler_taobao_images:def __init__(self):self.query_url = 'https://s.taobao.com/search?q={}&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20210913&ie=utf8'chrome_options = webdriver.ChromeOptions()chrome_options.add_argument("--disable-infobars")chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])chrome_options.add_argument('--headless')self.driver = webdriver.Chrome(options=chrome_options)self.sleep_time = 3self.save_img_path = 'result/'if os.path.exists(self.save_img_path):shutil.rmtree(self.save_img_path)os.makedirs(self.save_img_path)self.image_index = 0def run(self):querys = ['酒']for query in querys:site_url = self.query_url.format(query)self.getPage(site_url)def getPage(self, site_url):self.driver.get(site_url)time.sleep(self.sleep_time)print(self.driver.title)self.getItem(site_url)def getItem(self,site_url):html = self.driver.page_source.encode('utf-8')print('start parse the html')selector = etree.HTML(html)#itemList = selector.xpath("//div[@class='item J_MouseOnverReq ')/div[1]/")itemList = selector.xpath("//*[@id='mainsrp-itemlist']/div/div/div[1]/*")# 循环遍历该页所有商品for item in itemList:link = item.xpath("./div[contains(@class, 'pic-box')]/div[contains(@class, 'pic-box-inner')]/div[@class='pic']/a/@href")[0]if "https://" not in link:link = "https://" + linkprint("into: ", link)# 进入宝贝详情页 开始爬取里面的图片资料try:self.getItemDetail(link)except:print("get link {} error!!!".format(link))# 获取分页信息next_page_value = selector.xpath("//*[@id='mainsrp-pager']/div/div/div/ul/li[contains(@class,'next')]/a/@data-value")print("next page: ", next_page_value)if len(next_page_value) == 0:print('没有下一页了')else:site_url_p = site_url + '&s={}'.format(next_page_value[0])print('加载下一页内容:', site_url_p)self.getPage(site_url_p)def getItemDetail(self, link):chrome_options = webdriver.ChromeOptions()chrome_options.add_argument("--disable-infobars")chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])chrome_options.add_argument('--headless')newDriver = webdriver.Chrome(options=chrome_options)newDriver.get(link)time.sleep(self.sleep_time)print(newDriver.title)html = newDriver.page_source.encode('utf-8')selector = etree.HTML(html)# 获取图片略缩链接image_srcs = selector.xpath("//div[@class='tb-thumb-content']/ul/li/a/img/@src")for image_src in image_srcs:# 找较高分辨率的图片image_src = image_src.replace('60x60','430x430')imglink = 'https:' + image_srcprint('imglink:{}'.format(imglink))image_path = os.path.join(self.save_img_path, '{}.jpg'.format(self.image_index))self.saveImg(imglink, image_path)with open(image_path, 'wb') as f:f.write(requests.get(imglink).content)self.image_index += 1newDriver.quit()if __name__ == '__main__':# 修改keyword便可以修改搜索关键词 建议也修改存储目录tb = Crawler_taobao_images()tb.run()

【爬虫】python使用selenium抓取淘宝中的商品数据相关推荐

  1. Python爬虫实战八之利用Selenium抓取淘宝匿名旺旺

    其实本文的初衷是为了获取淘宝的非匿名旺旺,在淘宝详情页的最下方有相关评论,含有非匿名旺旺号,快一年了淘宝都没有修复这个. 很多人学习python,不知道从何学起. 很多人学习python,掌握了基本语 ...

  2. 爬虫学习笔记——Selenium爬取淘宝商品信息并保存

    在使用selenium来模拟浏览器操作,抓取淘宝商品信息前,先完成一些准备工作. 准备工作:需要安装selenium,pyquery,以及Chrome浏览器并配置ChromeDriver. 安装sel ...

  3. python3 爬虫实战案例 (抓取淘宝信息)(淘宝加了搜索必须登录的验证,此方法所到的结果都是0)

    需求:对比足球,篮球,乒乓球,羽毛球,网球,相关物品的销售量保存到excle中 和抓取淘宝关键字相关信息的销售量,这和之前抓取csdn网站浏览量取不同,抓取csdn浏览量主要是通过bs4Tag标签,而 ...

  4. 抓取淘宝天猫的商品的促销价格

    通过商品的url获取促销价,天猫淘宝的促销价并不是直接生成的,而是通过js间接生成的.所以通过jsoup等工具无法抓取. 首先是尝试使用htmlUnit,因为其可以,模拟浏览器运行js.css.经试验 ...

  5. Python开源爬虫项目代码:抓取淘宝、京东、QQ、知网数据--转

    数据来源:数据挖掘入门与实战  公众号: datadw scrapy_jingdong[9]- 京东爬虫.基于scrapy的京东网站爬虫,保存格式为csv.[9]: https://github.co ...

  6. python开源爬虫项目违法吗_Python开源爬虫项目代码:抓取淘宝、京东、QQ、知网数据...

    数据挖掘入门与实战 公众号: datadw scrapy_jingdong[9]- 京东爬虫.基于scrapy的京东网站爬虫,保存格式为csv.[9]: https://github.com/taiz ...

  7. Python爬虫淘宝基于selenium抓取淘宝商品数据2021年测试过滑动验证

    配置一下"可能需要修改的参数",就可以食用底部代码了,ps:可能已失效 本文章代码功能 准备工作 Python用到的库和准备工作 可能需要修改的参数 在CMD中打开一个Chrome ...

  8. python淘宝爬虫_简单的抓取淘宝图片的Python爬虫

    写了一个抓taobao图片的爬虫,全是用if,for,while写的,比较简陋,入门作品. 从网页http://mm.taobao.com/json/request_top_list.htm?type ...

  9. 使用python的selenium爬取淘宝标题价格,就算小白也能看懂的教学!!

    第一步 爬取前准备 安装selenium,以及如何启动自动控制请看下一章. 打开淘宝页面按下F12,即可跳出控制台(开发者模式),这里只要你技术好,网页上的资料你都能轻松获取.温馨提示:爬虫爬的好,牢 ...

最新文章

  1. 根据JSON自动生成select联动
  2. T-SQL查询进阶--流程控制语句
  3. 数据分析之pandas常见的数据处理(四)
  4. 李开复:数位革命——创新创业的黄金时代
  5. 指数随机变量 泊松过程跳_《常见随机过程》(一)
  6. 语音用户界面基本设计原则
  7. LiveVideoStack线上分享第五季(一):企业视频会议场景下的流量分发和弱网优化...
  8. 数论 —— 佩尔方程与连分数
  9. [分享]iOS开发-实现UILabel显示出不同颜色并且某一部分产生下划线的效果 ...
  10. 【干货】小米用户画像实战.pdf(附下载链接)
  11. python 组合求和_39. 组合总和(Python)
  12. easyui datagrid 点击其它 单元格,不让头列 checkbook 选中
  13. 去掉磁盘写保护小技巧
  14. mp4视频解码生成图片
  15. 24.树莓派交叉编译工具链的安装
  16. 微商城支付开发(二)
  17. 使用VB合并word文档内容
  18. 社招和校招有什么不同?阿里美团等大厂JAVA社招面经分享!
  19. MySQL-HA高可用
  20. 寻找市场中的Alpha-WorldQuant功能的实现(下)

热门文章

  1. UDS诊断系列之三 ISO14229协议介绍(下)
  2. python有哪些细节描写_2019中考作文指导-细节描写.ppt
  3. 轮胎规格怎么看?“3T”指数到底是什么?换轮胎前必读!
  4. 苹果鼠标怎么充电_“智能”还是“多功能”?米物智能鼠标垫测评
  5. 万网主机不支持php,万网等虚拟主机不能SMTP发信的解决方案
  6. iOS自定义相机实现拍照和连拍
  7. python中 什么意思_请问python中%代表什么意思?
  8. mysql数据库技术_MySQL数据库操作技术大全
  9. 2019年湖南电网考试备考(计算机专业第一批次)
  10. Java spring基于XML的aop配置实现