使用Python 爬取京东、淘宝等商品详情页的数据,避开反爬虫机制

以下是爬取京东商品详情的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:UsersnewYearDesktop爬图.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:python3Scriptschromedriver.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:UsersnewYearDesktop爬图.xlsx')

淘宝有两个问题,一个是需要绑定账号登录访问。这里是代码断点。然后手动走过授权。

第二个是被休息和懒惰加载。被休息。其实没影响的。一个页面结构已经加载出来了。然后也不会影响访问其他的页面。

至于懒惰加载嘛。对我们也没啥影响。如果不是直接写在src里那就在判断一次取 data-ks-lazyload就出来了。

最后就是爬取的片段截图

建议还是直接将爬取的数据存服务器,数据库,或者图片服务器。因为程序挺靠谱的。一万条数据。爬了26个G的文件。最后上传的时候差点累死了

是真的大。最后还要拆包。十几个2g压缩包一个一个上传。才成功。

原文地址:https://www.toutiao.com/article/7051459021718487556/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


本文从多个角度分析了vi编辑器保存退出命令。我们介绍了保存和退出vi编辑器的命令,以及如何撤销更改、移动光标、查找和替换文本等实用命令。希望这些技巧能帮助你更好地使用vi编辑器。
Python中的回车和换行是计算机中文本处理中的两个重要概念,它们在代码编写中扮演着非常重要的角色。本文从多个角度分析了Python中的回车和换行,包括回车和换行的概念、使用方法、使用场景和注意事项。通过本文的介绍,读者可以更好地理解和掌握Python中的回车和换行,从而编写出更加高效和规范的Python代码。
SQL Server启动不了错误1067是一种比较常见的故障,主要原因是数据库服务启动失败、权限不足和数据库文件损坏等。要解决这个问题,我们需要检查服务日志、重启服务器、检查文件权限和恢复数据库文件等。在日常的数据库运维工作中,我们应该时刻关注数据库的运行状况,及时发现并解决问题,以确保数据库的正常运行。
信息模块是一种可重复使用的、可编程的、可扩展的、可维护的、可测试的、可重构的软件组件。信息模块的端接需要从接口设计、数据格式、消息传递、函数调用等方面进行考虑。信息模块的端接需要满足高内聚、低耦合的原则,以保证系统的可扩展性和可维护性。
本文从电脑配置、PyCharm版本、Java版本、配置文件以及程序冲突等多个角度分析了Win10启动不了PyCharm的可能原因,并提供了解决方法。
本文主要从多个角度分析了安装SQL Server 2012时可能出现的错误,并提供了解决方法。
Pycharm是一款非常优秀的Python集成开发环境,它可以让Python开发者更加高效地进行代码编写、调试和测试。在Pycharm中设置解释器非常简单,我们可以通过创建新项目、修改项目解释器、设置全局解释器等多种方式进行设置。
Python中有多种方法可以将字符串转换为整数,包括使用int()函数、try-except语句、正则表达式、map()函数、ord()函数和reduce()函数。在实际应用中,应根据具体情况选择最合适的方法。
本文介绍了导入CSV文件的多种方法,包括使用Excel、Python和R等工具。同时,还介绍了导入CSV文件时需要注意的一些细节和问题。CSV文件是数据处理和分析中不可或缺的一部分,希望本文能够对读者有所帮助。
mongodb是一种新型的数据库,它采用了面向文档的数据模型,具有灵活性、高性能和高可用性等优势。但是,mongodb也存在数据结构混乱、安全性和学习成本高等问题。
当Python运行不了时,我们应该从代码、Python环境、操作系统和硬件设备等多个角度来排查问题,并采取相应的解决措施。
Python列表是一种常见的数据类型,排序是列表操作中的一个重要部分。本文介绍了Python列表降序排序的方法,包括使用sort()函数、sorted()函数以及自定义函数进行排序。使用sort()函数可以简单方便地实现降序排序,但会改变原始列表的顺序;使用sorted()函数可以保留原始列表的顺序,但需要创建一个新的列表;使用自定义函数可以灵活地控制排序的方式,但需要编写额外的代码。
本文介绍了如何使用Python输入一段英文并统计其中的单词个数,从去除标点符号、忽略单词大小写、排除常用词汇等多个角度进行了分析。此外,还介绍了使用NLTK库进行单词统计的方法。
虚拟环境可以帮助我们在同一台机器上运行不同版本的Python、安装不同的Python包,并且不会相互影响。创建虚拟环境的命令是python3 -m venv myenv,进入虚拟环境的命令是source myenv/bin/activate,退出虚拟环境的命令是deactivate。在虚拟环境中可以使用pip安装包,也可以使用Python运行程序。
本文从XHR对象、fetch API和jQuery三个方面分析了JS获取响应状态的方法及其应用。以上三种方法都可以轻松地发送HTTP请求,并处理响应数据。
桌面的命令包括常见的操作命令、系统命令、批处理命令以及第三方应用程序提供的命令。我们可以通过鼠标右键点击桌面、创建快捷方式、创建批处理文件等方式来运用这些命令,从而更好地管理计算机,提高工作效率。
本文分析了应用程序闪退的多个原因,包括应用程序本身存在问题、手机或平板电脑系统问题、硬件问题、网络问题和其他原因。同时,本文提供了解决闪退问题的多种方式,包括更新或卸载重新下载应用程序、升级系统或进行修复、清理手机缓存、清理不必要的文件或者是更换电池等方式来解决、确保网络信号的稳定性、注意用户隐私和安全问题。
本文介绍了使用Python下载图片的多种方法,包括使用Python标准库urllib.request、第三方库requests、多线程和异步IO。这些方法在不同情况下都有它们的优缺点。使用这些方法,我们可以轻松地将网络上的图片下载到本地,方便我们在离线状态下查看或处理这些图片。
MySQL数据文件是指存储MySQL数据库中数据的文件,存储位置的选择对数据库的性能、可靠性和安全性都有着重要的影响。本文从存储位置的选择、存储设备的选择、存储空间的管理和存储位置的安全性等多个角度对MySQL数据文件的存储位置进行分析,最后得出需要根据实际情况综合考虑多个因素,选择合适的存储位置和存储设备,并进行有效的存储空间管理和安全措施的结论。
AS400是一种主机操作系统,每个库都包含多个表。查询库表总数是一项基本任务。可以使用命令行、系统管理界面以及数据库管理工具来查询库表总数。查询库表总数可以帮助用户更好地管理和优化数据,包括规划数据存储、优化查询性能以及管理空间资源。