使用Python 爬取京东、淘宝等商品详情页的数据,避开反爬虫机制
itomcoil 2024-12-18 14:54 27 浏览
以下是爬取京东商品详情的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压缩包一个一个上传。才成功。
相关推荐
- CentOS7服务器,这样搭建Tensorflow很快!我可以提前去吃饭了
-
CentOS7搭建Tensorflow框架凡是我相信的,我都做了;凡是我做了的事,都是全身心地投入去做的。WhateverIbelieved,Idid;andwhateverIdid,...
- python2.0和python3.0的区别(python2.7和3.7哪个好)
-
Python3.0是Python语言的一次重大升级,与Python2.x系列存在许多不兼容的改动。以下是两者核心区别的全面总结,按重要性和使用频率排序:一、最关键的破坏性变更特性Pyth...
- 体验无GIL的自由线程Python:Python 3.13 新特征之一
-
全局解释器锁(GIL,GlobalInterpreterLock)是Python中备受争议的特性之一。它的主要作用是确保Python是一种线程安全的编程语言,防止多个线程同时访问和修改同一...
- Python 3.8异步并发编程指南(python异步调用)
-
有效的提高程序执行效率的两种方法是异步和并发,Golang,node.js之所以可以有很高执行效率主要是他们的协程和异步并发机制。实际上异步和并发是每一种现代语言都在追求的特性,当然Python也不例...
- Python测试框架pytest入门基础(pytest框架搭建)
-
Pytest简介Pytestisamaturefull-featuredPythontestingtoolthathelpsyouwritebetterprograms.T...
- Python学不会来打我(8)字符串string类型深度解析
-
2025年全球开发者调查显示,90%的Python项目涉及字符串处理,而高效使用字符串可提升代码效率40%。本文系统拆解字符串核心操作,涵盖文本处理、数据清洗、模板生成等八大场景,助你掌握字符串编程精...
- windows使用pyenv安装多python版本环境
-
官方的介绍。pyenvletsyoueasilyswitchbetweenmultipleversionsofPython.It’ssimple,unobtrusive,an...
- Python 中 base64 编码与解码(Python 中 base64 编码与解码生成)
-
base64是经常使用的一种加密方式,在Python中有专门的库支持。本文主要介绍在Python2和Python3中的使用区别:在Python2环境:Python2.7.16(d...
- Python项目整洁的秘诀:深入理解__init__.py文件
-
当你发现项目中import语句越来越混乱时,问题可能出在缺少这个关键文件上作为一名Python开发者,我曾深陷项目结构混乱的困境。直到真正理解了__init__.py文件的价值,我的代码世界才变得井然...
- 如何把一个Python应用程序装进Docker
-
准备容器无处不在,但是如何在Docker容器中运行Python应用程序呢?这篇文章将告诉你怎么做!如果您想知道,这些示例需要Python3.x。在深入讨论容器之前,让我们进一步讨论一下我们想要封装的...
- python中数值比较大小的8种经典比较方法,不允许你还不知道
-
在Python中比较数值大小是基础但重要的操作。以下是8种经典比较方法及其应用场景,从基础到进阶的完整指南:1.基础比较运算符Python提供6种基础比较运算符:a,b=5,3...
- Python程序员必看3分钟掌握if语句10个神技,第5个99%的人不知道
-
同事因为写错一个if被开除?全网疯传的Python避坑指南,看完我连夜改了代码!一、新手必踩的3大天坑(附救命代码)技巧1:缩进踩坑事件ifTrue:print("这样写必报错!...
- 为什么Python里遍历字符串比列表慢?3个底层原因揭秘
-
用字符串处理文本时,你可能正悄悄浪费性能。在日常Python开发中,我们经常需要遍历字符串和列表。但你是否注意过,当处理海量数据时,遍历字符串的速度明显比列表慢?这背后隐藏着Python设计的深层逻辑...
- 记录Python3.7.4更新到Python.3.7.8
-
Python官网Python安装包下载下载文件名称运行后选择升级选项等待安装安装完毕打开IDLE使用Python...
- Python3中最常用的5种线程锁你会用吗
-
前言本章节将继续围绕threading模块讲解,基本上是纯理论偏多。对于日常开发者来讲很少会使用到本章节的内容,但是对框架作者等是必备知识,同时也是高频的面试常见问题。私信小编01即可获取大量Pyth...
- 一周热门
- 最近发表
-
- CentOS7服务器,这样搭建Tensorflow很快!我可以提前去吃饭了
- python2.0和python3.0的区别(python2.7和3.7哪个好)
- 体验无GIL的自由线程Python:Python 3.13 新特征之一
- Python 3.8异步并发编程指南(python异步调用)
- Python测试框架pytest入门基础(pytest框架搭建)
- Python学不会来打我(8)字符串string类型深度解析
- windows使用pyenv安装多python版本环境
- Python 中 base64 编码与解码(Python 中 base64 编码与解码生成)
- Python项目整洁的秘诀:深入理解__init__.py文件
- 如何把一个Python应用程序装进Docker
- 标签列表
-
- 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)
- shutil.copy() (33)