使用Python 爬取京东、淘宝等商品详情页的数据,避开反爬虫机制
off999 2024-10-04 18:53 19 浏览 0 评论
以下是爬取京东商品详情的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压缩包一个一个上传。才成功。
相关推荐
- SPC相关的计算用excel和python实现【源码下载】
-
做SPC分析涉及到很多计算,比如CPK、PPK、概率图、PPM等等,网上很多公式,但具体实现却不是那么容易的。我们整理了这些用excel和python实现的代码。包括但不限于以下的内容:SPC分析中的...
- Python学不会来打我(34)python函数爬取百度图片_附源码
-
随着人工智能和大数据的发展,图像数据的获取变得越来越重要。作为Python初学者,掌握如何从网页中抓取图片并保存到本地是一项非常实用的技能。本文将手把手教你使用Python函数编写一个简单的百度图片...
- django python数据中心、客户、机柜、设备资源管理平台源码分享
-
先转发后关注,私信“资源”即可免费获取源码下载链接!本项目一个开源的倾向于数据中心运营商而开发的,拥有数据中心、客户、机柜、设备、跳线、物品、测试、文档等一些列模块的资源管理平台,解决各类资源集中管理...
- 熬夜也值得学习练手的108个Python项目(附源码),太实用了!
-
现在学编程的人越来越多,Python因为简单好上手、功能又强大,成了很多人的首选。不管是做数据分析、人工智能,还是写网络程序、自动化脚本,Python都能派上用场。而且它诞生的时间比网页还早,作为...
- 这五个办公室常用自动化工具python源码,复制代码就能用
-
办公室自动化现在能看这文章的恐怕大部分都是办公室久坐工作者,很多都有腰肌劳损、肩周炎等职业病,难道就不能有个工具缓解一下工作量吗?那么恭喜你点进了这篇文章,这篇文章将使用python直接实现五个常...
- 将python源代码封装成window可执行程序教程
-
将python源代码封装成window可执行程序教程点击键盘win+r打开运行框在运行框中输入cmd,进入到命令行。在命令行中输入piplist去查看当前电脑中所有的库检查是否有pyinstall...
- Python 爬虫如何爬取网页源码?(爬虫获取网页源代码)
-
下面教大家用几行代码轻松爬取百度首页源码。什么是urllib?urllib库是Python内置的HTTP请求库,它可以看做是处理URL的组件集合。urllib库包含了四大模块,具体如下:urllib....
- Python RPC 之 Thrift(python是做什么的)
-
thrift-0.12.0python3.4.3Thrift简介:Thrift是一款高性能、开源的RPC框架,产自Facebook后贡献给了Apache,Thrift囊括了整个RP...
- 用Python编写FPGA以太网MAC(附源码下载方式)
-
来源:EETOP作者:ccpp123略作了解后发现,MyHDL不是高层次综合,它实际上是用Python的一些功能实现了一个Verilog仿真器,能对用Python写的仿Verilog语言进行仿...
- python爬虫常用工具库总结(python爬虫工具下载)
-
说起爬虫,大家可能第一时间想到的是python,今天就简单为大家介绍下pyhton常用的一些库。请求库:实现基础Http操作urllib:python内置基本库,实现了一系列用于操作url的功能。...
- 手把手教你使用scrapy框架来爬取北京新发地价格行情(理论篇)
-
来源:Python爬虫与数据挖掘作者:霖hero大家好!我是霖hero。上个月的时候,我写了一篇关于IP代理的文章,手把手教你使用XPath爬取免费代理IP,今天在这里分享我的第二篇文章,希望大家可以...
- 2025年Python爬虫学习路线:第1阶段 爬虫基础入门开始
-
这个阶段的目标是让你熟悉Python的基础知识、了解HTTP请求和HTML是如何工作的,并最终完成你的第一个爬虫小项目——抓取名言!按照计划,我们首先要打好Python基础。Python就像是我们要...
- 如何入门 Python 爬虫?(python零基础爬虫)
-
1.很多人一上来就要爬虫,其实没有弄明白要用爬虫做什么,最后学完了却用不上。大多数人其实是不需要去学习爬虫的,因为工作所在的公司里有自己的数据库,里面就有数据来帮助你完成业务分析。什么时候要用到爬虫呢...
- 突破爬虫瓶颈:Python爬虫核心能力提升与案例实操
-
技术控必看!Python爬虫高手进阶全攻略,解锁数据处理高阶玩法在数字化时代,Python爬虫早已成为数据探索者手中的得力工具。从基础的网页抓取到复杂的数据处理,每一次技术升级都能带来新的突破。本文将...
- 网络爬虫开源框架(网络爬虫的框架)
-
目前开源爬虫下载框架是百花齐放,各个编程语言都有,以下主要介绍其中重要的几个:1)python:scrapy,pyspider,gcrawler2)Java:webmagic,WebCollector...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- SPC相关的计算用excel和python实现【源码下载】
- Python学不会来打我(34)python函数爬取百度图片_附源码
- django python数据中心、客户、机柜、设备资源管理平台源码分享
- 熬夜也值得学习练手的108个Python项目(附源码),太实用了!
- 这五个办公室常用自动化工具python源码,复制代码就能用
- 将python源代码封装成window可执行程序教程
- Python 爬虫如何爬取网页源码?(爬虫获取网页源代码)
- Python RPC 之 Thrift(python是做什么的)
- 用Python编写FPGA以太网MAC(附源码下载方式)
- python爬虫常用工具库总结(python爬虫工具下载)
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python自定义函数 (53)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python字典增加键值对 (53)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python人脸识别 (54)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)