使用Python 爬取京东、淘宝等商品详情页的数据,避开反爬虫机制
itomcoil 2024-12-18 14:54 21 浏览
以下是爬取京东商品详情的Python3代码,以excel存放链接的方式批量爬取。excel如下
代码如下
私信小编01即可获取大量Python学习资源
from selenium import webdriver
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import datetime
import calendar
import logging
from logging import handlers
import requests
import os
import time
import pymssql
import openpyxl
import xlrd
import codecs
class EgongYePing:
options = webdriver.FirefoxOptions()
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","application/zip,application/octet-stream")
global driver
driver= webdriver.Firefox(firefox_profile=fp,options=options)
def Init(self,url,code):
print(url.strip())
driver.get(url.strip())
#driver.refresh()
# 操作浏览器属于异步,在网络出现问题的时候。可能代码先执行。但是请求页面没有应答。所以硬等
time.sleep(int(3))
html = etree.HTML(driver.page_source)
if driver.title!=None:
listImg=html.xpath('//*[contains(@class,"spec-list")]//ul//li//img')
if len(listImg)==0:
pass
if len(listImg)>0:
imgSrc=''
for item in range(len(listImg)):
imgSrc='https://img14.360buyimg.com/n0/'+listImg[item].attrib["data-url"]
print('头图下载:'+imgSrc)
try:
Headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r = requests.get(imgSrc, headers=Headers, stream=True)
if r.status_code == 200:
imgUrl=''
if item==0:
imgUrl+=code + "_主图_" + str(item) + '.' + imgSrc.split('//')[1].split('/')[len(imgSrc.split('//')[1].split('/'))-1].split('.')[1]
else:
imgUrl+=code + "_附图_" + str(item) + '.' + imgSrc.split('//')[1].split('/')[len(imgSrc.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl , 'wb').write(r.content) # 将内容写入图片
del r
except Exception as e:
print("图片禁止访问:"+imgSrc)
listImg=html.xpath('//*[contains(@class,"ssd-module")]')
if len(listImg)==0:
listImg=html.xpath('//*[contains(@id,"J-detail-content")]//div//div//p//img')
if len(listImg)==0:
listImg=html.xpath('//*[contains(@id,"J-detail-content")]//img')
if len(listImg)>0:
for index in range(len(listImg)):
detailsHTML=listImg[index].attrib
if 'data-id' in detailsHTML:
try:
details= driver.find_element_by_class_name("animate-"+listImg[index].attrib['data-id']).value_of_css_property('background-image')
details=details.replace('url(' , ' ')
details=details.replace(')' , ' ')
newDetails=details.replace('"', ' ')
details=newDetails.strip()
print("详情图下载:"+details)
try:
Headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r = requests.get(details, headers=Headers, stream=True)
if r.status_code == 200:
imgUrl=''
imgUrl+=code + "_详情图_" + str(index) + '.' + details.split('//')[1].split('/')[len(details.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl, 'wb').write(r.content) # 将内容写入图片
del r
except Exception as e:
print("图片禁止访问:"+details)
except Exception as e:
print('其他格式的图片不收录');
if 'src' in detailsHTML:
try:
details= listImg[index].attrib['src']
if 'http' in details:
pass
else:
details='https:'+details
print("详情图下载:"+details)
try:
Headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r = requests.get(details, headers=Headers, stream=True)
if r.status_code == 200:
imgUrl=''
imgUrl+=code + "_详情图_" + str(index) + '.' + details.split('//')[1].split('/')[len(details.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl, 'wb').write(r.content) # 将内容写入图片
del r
except Exception as e:
print("图片禁止访问:"+details)
except Exception as e:
print('其他格式的图片不收录');
print('结束执行')
@staticmethod
def readxlsx(inputText):
filename=inputText
inwb = openpyxl.load_workbook(filename) # 读文件
sheetnames = inwb.get_sheet_names() # 获取读文件中所有的sheet,通过名字的方式
ws = inwb.get_sheet_by_name(sheetnames[0]) # 获取第一个sheet内容
# 获取sheet的最大行数和列数
rows = ws.max_row
cols = ws.max_column
for r in range(1,rows+1):
for c in range(1,cols):
if ws.cell(r,c).value!=None and r!=1 :
if 'item.jd.com' in str(ws.cell(r,c+1).value) and str(ws.cell(r,c+1).value).find('i-item.jd.com')==-1:
print('支持:'+str(ws.cell(r,c).value)+'|'+str(ws.cell(r,c+1).value))
EgongYePing().Init(str(ws.cell(r,c+1).value),str(ws.cell(r,c).value))
else:
print('当前格式不支持:'+(str(ws.cell(r,c).value)+'|'+str(ws.cell(r,c+1).value)))
pass
pass
if __name__ == "__main__":
start = EgongYePing()
start.readxlsx(r'C:\Users\newYear\Desktop\爬图.xlsx')
基本上除了过期的商品无法访问以外。对于京东的三种页面结构都做了处理。能访问到的商品页面。还做了模拟浏览器请求访问和下载。基本不会被反爬虫屏蔽下载。
上面这一段是以火狐模拟器运行
上面这一段是模拟浏览器下载。如果不加上这一段。经常会下载几十张图片后,很长一段时间无法正常下载图片。因为没有请求头被认为是爬虫。
上面这段是京东的商品详情页面,经常会三种?(可能以后会更多的页面结构)
所以做了三段解析。只要没有抓到图片就换一种解析方式。这杨就全了。
京东的图片基本只存/1.jpg。然后域名是 https://img14.360buyimg.com/n0/。所以目前要拼一下。
京东还有个很蛋疼的地方是图片以data-id拼进div的背景元素里。所以取出来的时候要绕一下。还好也解决了。
以下是爬取京东商品详情的Python3代码,以excel存放链接的方式批量爬取。excel如下
因为这次是淘宝和京东一起爬取。所以在一个excel里。代码里区分淘宝和京东的链接。以下是代码
from selenium import webdriver
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import datetime
import calendar
import logging
from logging import handlers
import requests
import os
import time
import pymssql
import openpyxl
import xlrd
import codecs
class EgongYePing:
options = webdriver.FirefoxOptions()
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","application/zip,application/octet-stream")
global driver
driver= webdriver.Firefox(firefox_profile=fp,options=options)
def Init(self,url,code):
#driver = webdriver.Chrome('D:\python3\Scripts\chromedriver.exe')
#driver.get(url)
print(url.strip())
driver.get(url.strip())
#driver.refresh()
# 操作浏览器属于异步,在网络出现问题的时候。可能代码先执行。但是请求页面没有应答。所以硬等
time.sleep(int(3))
html = etree.HTML(driver.page_source)
if driver.title!=None:
listImg=html.xpath('//*[contains(@id,"J_UlThumb")]//img')
if len(listImg)==0:
pass
if len(listImg)>0:
imgSrc=''
for item in range(len(listImg)):
search=listImg[item].attrib
if 'data-src' in search:
imgSrc=listImg[item].attrib["data-src"].replace('.jpg_50x50','')
else:
imgSrc=listImg[item].attrib["src"]
if 'http' in imgSrc:
pass
else:
imgSrc='https:'+imgSrc
print('头图下载:'+imgSrc)
try:
Headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r = requests.get(imgSrc, headers=Headers, stream=True)
if r.status_code == 200:
imgUrl=''
if item==0:
imgUrl+=code + "_主图_" + str(item) + '.' + imgSrc.split('//')[1].split('/')[len(imgSrc.split('//')[1].split('/'))-1].split('.')[1]
else:
imgUrl+=code + "_附图_" + str(item) + '.' + imgSrc.split('//')[1].split('/')[len(imgSrc.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl , 'wb').write(r.content) # 将内容写入图片
del r
except Exception as e:
print("图片禁止访问:"+imgSrc)
listImg=html.xpath('//*[contains(@id,"J_DivItemDesc")]//img')
if len(listImg)>0:
for index in range(len(listImg)):
detailsHTML=listImg[index].attrib
if 'data-ks-lazyload' in detailsHTML:
details= listImg[index].attrib["data-ks-lazyload"]
print("详情图下载:"+details)
else:
details= listImg[index].attrib["src"]
print("详情图下载:"+details)
try:
Headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
r = requests.get(details, headers=Headers, stream=True)
if r.status_code == 200:
imgUrl=''
details=details.split('?')[0]
imgUrl+=code + "_详情图_" + str(index) + '.' + details.split('//')[1].split('/')[len(details.split('//')[1].split('/'))-1].split('.')[1]
open(os.getcwd()+'/img/'+ imgUrl, 'wb').write(r.content) # 将内容写入图片
del r
except Exception as e:
print("图片禁止访问:"+details)
print('结束执行')
@staticmethod
def readxlsx(inputText):
filename=inputText
inwb = openpyxl.load_workbook(filename) # 读文件
sheetnames = inwb.get_sheet_names() # 获取读文件中所有的sheet,通过名字的方式
ws = inwb.get_sheet_by_name(sheetnames[0]) # 获取第一个sheet内容
# 获取sheet的最大行数和列数
rows = ws.max_row
cols = ws.max_column
for r in range(1,rows+1):
for c in range(1,cols):
if ws.cell(r,c).value!=None and r!=1 :
if 'item.taobao.com' in str(ws.cell(r,c+1).value):
print('支持:'+str(ws.cell(r,c).value)+'|'+str(ws.cell(r,c+1).value))
EgongYePing().Init(str(ws.cell(r,c+1).value),str(ws.cell(r,c).value))
else:
print('当前格式不支持:'+(str(ws.cell(r,c).value)+'|'+str(ws.cell(r,c+1).value)))
pass
pass
if __name__ == "__main__":
start = EgongYePing()
start.readxlsx(r'C:\Users\newYear\Desktop\爬图.xlsx')
淘宝有两个问题,一个是需要绑定账号登录访问。这里是代码断点。然后手动走过授权。
第二个是被休息和懒惰加载。被休息。其实没影响的。一个页面结构已经加载出来了。然后也不会影响访问其他的页面。
至于懒惰加载嘛。对我们也没啥影响。如果不是直接写在src里那就在判断一次取 data-ks-lazyload就出来了。
最后就是爬取的片段截图
建议还是直接将爬取的数据存服务器,数据库,或者图片服务器。因为程序挺靠谱的。一万条数据。爬了26个G的文件。最后上传的时候差点累死了
是真的大。最后还要拆包。十几个2g压缩包一个一个上传。才成功。
相关推荐
- PS小技巧 调整命令,让人物肤色变得更加白皙 #后期修图
-
我们来看一下如何去将人物的皮肤变得更加的白皙。·首先选中图层,Ctrl键加J键复制一层。·打开这里的属性面板,选择快速操作删除背景,这样就会将人物进行单独的抠取。·接下来在上方去添加一个黑白调整图层,...
- 把人物肤色提亮的方法和技巧
-
PS后期调白肤色提亮照片的方法。一白遮百丑,所以对于Photoshop后期来说把人物肤色调白是一项非常重要的任务。就拿这张素材图片来说,这张素材图片人脸的肤色主要偏红、偏黄,也不够白皙,该怎样对它进行...
- 《Photoshop教程》把美女图片调成清爽色彩及润肤技巧
-
关注PS精品教程,每天不断更新~~室内人物图片一般会偏暗,人物脸部、肤色及背景会出现一些杂点。处理之前需要认真的给人物磨皮及美白,然后再整体润色。最终效果原图一、用修补工具及图章工具简单去除大一点的黑...
- PS后期对皮肤进行美白的技巧
-
PS后期进行皮肤美白的技巧。PS后期对皮肤进行美白的技巧:·打开素材图片之后直接复制原图。·接下来直接点击上方的图像,选择应用图像命令。·在通道这里直接选择红通道,混合这里直接选择柔光,然后点击确定。...
- 493 [PS调色]调模特通透肤色
-
效果对比:效果图吧:1、光位图:2、拍摄参数:·快门:160;光圈:8;ISO:1003、步骤分解图:用曲线调整图层调出基本色调。用可选颜色调整图层调整红色、黄色、白色和灰色4种颜色的混合比例。用色彩...
- 先选肤色再涂面部,卡戴珊的摄影师透露:为明星拍完照后怎么修图
-
据英国媒体12月17日报道,真人秀明星金·卡戴珊终于承认,她把女儿小北P进了家族的圣诞贺卡,怪不得粉丝们都表示这张贺卡照得非常失败。上周,这位39岁的女星遭到了一些粉丝针对这张照片的批评,她于当地时间...
- 如何在PS中运用曲线复制另一张照片的色调
-
怎样把另一张作品的外观感觉,套用到自己的照片上?单靠肉眼来猜,可能很不容易,而来自BenSecret的教学,关键是在PS使用了两个工具,让你可以准确比较两张照片的曝光、色调与饱和度,方便你调整及复制...
- PS在LAB模式下调出水嫩肤色的美女
-
本PS教程主要使用Photoshop使用LAB模式调出水嫩肤色的美女,教程调色比较独特。作者比较注重图片高光部分的颜色,增加质感及肤色调红润等都是在高光区域完成。尤其在Lab模式下,用高光选区调色后图...
- 在Photoshop图像后期处理中如何将人物皮肤处理得白皙通透
-
我们在人像后期处理中,需要将人物皮肤处理的白皙通透,处理方法很多,大多数都喜欢使用曲线、磨皮等进行调整,可以达到亮但是不透,最终效果往往不是很好,今天就教大家一种如何将任务皮肤处理得白皙通透,希望能帮...
- PS调色自学教程:宝宝照片快速调通透,简单实用!
-
PS调色自学教程:宝宝照片快速调通透。·首先复制图层,然后选择进入ACR滤镜,选择曲线锁定照片的亮部,也就高光位置,其他部位补亮一点,尤其是阴影的部位补亮多一些,让画面的层次均匀一点。·然后回到基本项...
- 【干货】如何利用PS进行人物美化
-
人物图像美化在Photoshop中非常常用,Photoshop作为一款功能强大的图像处理软件,不仅可以对人像进行基本的调色、美化和修复等处理,还可以改变人物的线条和幅度,如调整脸部器官和脸型的大小、调...
- 教大家一种可以快速把肤色处理均匀的方法@抖音短视频
-
快速把肤色处理均匀的方法。今天教大家一种可以快速把肤色处理均匀的方法。像这张照片整体肤色走紫红色,但是局部偏黄缘处理起来非常的麻烦。其实我们只需要新建空白图层,图层混合模式更改为颜色,再选择画笔工具把...
- PS调色教程 利用RAW调出干净通透的肤色
-
要么不发,要么干货。后期教程来噜~用RAW调出干净通透的肤色。这次终于不会原片比PS后好看了吧。如果你依然这么觉得,请不要残忍的告诉我这个事实,泪谢TAT)附送拍摄花絮,感谢各位的支持更多风格请关注m...
- photoshop后期皮肤变白的技巧
-
PS后期皮肤变白的技巧。1.PS后期让皮肤变白的方法有很多种,接下来教你一种非常简单容易上手的方法。2.打开素材图片之后,直接在小太极下拉框的位置添加一个纯色调整图层,颜色设置一个纯白色,点击...
- Photoshop调出人物的淡雅粉嫩肤色教程
-
本教程主要使用Photoshop调出人物的淡雅粉嫩肤色教程,最终的效果非常的通透迷人,下面让我们一起来学习.出自:86ps效果图:原图:1、打开原图复制一层。2、用Topaz滤镜磨皮(点此下载)。3、...
- 一周热门
- 最近发表
- 标签列表
-
- ps像素和厘米换算 (32)
- ps图案在哪里 (33)
- super().__init__ (33)
- python 获取日期 (34)
- 0xa (36)
- super().__init__()详解 (33)
- python安装包在哪里找 (33)
- linux查看python版本信息 (35)
- python怎么改成中文 (35)
- php文件怎么在浏览器运行 (33)
- eval在python中的意思 (33)
- python安装opencv库 (35)
- python div (34)
- sticky css (33)
- python中random.randint()函数 (34)
- python去掉字符串中的指定字符 (33)
- python入门经典100题 (34)
- anaconda安装路径 (34)
- yield和return的区别 (33)
- 1到10的阶乘之和是多少 (35)
- python安装sklearn库 (33)
- dom和bom区别 (33)
- js 替换指定位置的字符 (33)
- python判断元素是否存在 (33)
- sorted key (33)