Python爬取当当、京东、亚马逊图书信息代码实例

2023-10-28 15:59

本文主要是介绍Python爬取当当、京东、亚马逊图书信息代码实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这篇文章主要介绍了Python爬取当当、京东、亚马逊图书信息代码实例,具有一定借鉴价值,需要的朋友可以参考下。

注:

1.本程序采用MSSQLserver数据库存储,请运行程序前手动修改程序开头处的数据库链接信息

2.需要bs4、requests、pymssql库支持

3.支持多线程

from bs4 import BeautifulSoup import re,requests,pymysql,threading,os,traceback 
'''
更多Python学习资料以及源码教程资料,可以在群1136201545免费获取
'''try: conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='book',charset="utf8") cursor = conn.cursor() except: print('\n错误:数据库连接失败') #返回指定页面的html信息 def getHTMLText(url): try: headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'} r = requests.get(url,headers = headers) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return '' #返回指定url的Soup对象 def getSoupObject(url): try: html = getHTMLText(url) soup = BeautifulSoup(html,'html.parser') return soup except: return '' #获取该关键字在图书网站上的总页数 def getPageLength(webSiteName,url): try: soup = getSoupObject(url) if webSiteName == 'DangDang': a = soup('a',{'name':'bottom-page-turn'}) return a[-1].string elif webSiteName == 'Amazon': a = soup('span',{'class':'pagnDisabled'}) return a[-1].string except: print('\n错误:获取{}总页数时出错...'.format(webSiteName)) return -1class DangDangThread(threading.Thread): def __init__(self,keyword): threading.Thread.__init__(self) self.keyword = keyword def run(self): print('\n提示:开始爬取当当网数据...') count = 1length = getPageLength('DangDang','http://search.dangdang.com/?key={}'.format(self.keyword))#总页数 tableName = 'db_{}_dangdang'.format(self.keyword) try: print('\n提示:正在创建DangDang表...') cursor.execute('create table {} (id int ,title text,prNow text,prPre text,link text)'.format(tableName)) print('\n提示:开始爬取当当网页面...') for i in range(1,int(length)): url = 'http://search.dangdang.com/?key={}&page_index={}'.format(self.keyword,i) soup = getSoupObject(url) lis = soup('li',{'class':re.compile(r'line'),'id':re.compile(r'p')}) for li in lis: a = li.find_all('a',{'name':'itemlist-title','dd_name':'单品标题'}) pn = li.find_all('span',{'class': 'search_now_price'}) pp = li.find_all('span',{'class': 'search_pre_price'}) if not len(a) == 0: link = a[0].attrs['href'] title = a[0].attrs['title'].strip() else: link = 'NULL'title = 'NULL'if not len(pn) == 0: prNow = pn[0].string else: prNow = 'NULL'if not len(pp) == 0: prPre = pp[0].string else: prPre = 'NULL'sql = "insert into {} (id,title,prNow,prPre,link) values ({},'{}','{}','{}','{}')".format(tableName,count,title,prNow,prPre,link) cursor.execute(sql) print('\r提示:正在存入当当数据,当前处理id:{}'.format(count),end='') count += 1conn.commit() except: passclass AmazonThread(threading.Thread): def __init__(self,keyword): threading.Thread.__init__(self) self.keyword = keyword def run(self): print('\n提示:开始爬取亚马逊数据...') count = 1length = getPageLength('Amazon','https://www.amazon.cn/s/keywords={}'.format(self.keyword))#总页数 tableName = 'db_{}_amazon'.format(self.keyword) try: print('\n提示:正在创建Amazon表...') cursor.execute('create table {} (id int ,title text,prNow text,link text)'.format(tableName)) print('\n提示:开始爬取亚马逊页面...') for i in range(1,int(length)): url = 'https://www.amazon.cn/s/keywords={}&page={}'.format(self.keyword,i) soup = getSoupObject(url) lis = soup('li',{'id':re.compile(r'result_')}) for li in lis: a = li.find_all('a',{'class':'a-link-normal s-access-detail-page a-text-normal'}) pn = li.find_all('span',{'class': 'a-size-base a-color-price s-price a-text-bold'}) if not len(a) == 0: link = a[0].attrs['href'] title = a[0].attrs['title'].strip() else: link = 'NULL'title = 'NULL'if not len(pn) == 0: prNow = pn[0].string else: prNow = 'NULL'sql = "insert into {} (id,title,prNow,link) values ({},'{}','{}','{}')".format(tableName,count,title,prNow,link) cursor.execute(sql) print('\r提示:正在存入亚马逊数据,当前处理id:{}'.format(count),end='') count += 1conn.commit() except: passclass JDThread(threading.Thread): def __init__(self,keyword): threading.Thread.__init__(self) self.keyword = keyword def run(self): print('\n提示:开始爬取京东数据...') count = 1tableName = 'db_{}_jd'.format(self.keyword) try: print('\n提示:正在创建JD表...') cursor.execute('create table {} (id int,title text,prNow text,link text)'.format(tableName)) print('\n提示:开始爬取京东页面...') for i in range(1,100): url = 'https://search.jd.com/Search?keyword={}&page={}'.format(self.keyword,i) soup = getSoupObject(url) lis = soup('li',{'class':'gl-item'}) for li in lis: a = li.find_all('div',{'class':'p-name'}) pn = li.find_all('div',{'class': 'p-price'})[0].find_all('i') if not len(a) == 0: link = 'http:' + a[0].find_all('a')[0].attrs['href'] title = a[0].find_all('em')[0].get_text() else: link = 'NULL'title = 'NULL'if(len(link) > 128): link = 'TooLong'if not len(pn) == 0: prNow = '¥'+ pn[0].string else: prNow = 'NULL'sql = "insert into {} (id,title,prNow,link) values ({},'{}','{}','{}')".format(tableName,count,title,prNow,link) cursor.execute(sql) print('\r提示:正在存入京东网数据,当前处理id:{}'.format(count),end='') count += 1conn.commit() except : passdef closeDB(): global conn,cursor conn.close() cursor.close() def main(): print('提示:使用本程序,请手动创建空数据库:Book,并修改本程序开头的数据库连接语句') keyword = input("\n提示:请输入要爬取的关键字:") dangdangThread = DangDangThread(keyword) amazonThread = AmazonThread(keyword) jdThread = JDThread(keyword) dangdangThread.start() amazonThread.start() jdThread.start() dangdangThread.join() amazonThread.join() jdThread.join() closeDB() print('\n爬取已经结束,即将关闭....') os.system('pause') main()

示例截图:

关键词:Android下的部分运行结果(以导出至Excel)在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

这篇关于Python爬取当当、京东、亚马逊图书信息代码实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/294330

相关文章

基于Python开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

Python中图片与PDF识别文本(OCR)的全面指南

《Python中图片与PDF识别文本(OCR)的全面指南》在数据爆炸时代,80%的企业数据以非结构化形式存在,其中PDF和图像是最主要的载体,本文将深入探索Python中OCR技术如何将这些数字纸张转... 目录一、OCR技术核心原理二、python图像识别四大工具库1. Pytesseract - 经典O

基于Linux的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

Python打印对象所有属性和值的方法小结

《Python打印对象所有属性和值的方法小结》在Python开发过程中,调试代码时经常需要查看对象的当前状态,也就是对象的所有属性和对应的值,然而,Python并没有像PHP的print_r那样直接提... 目录python中打印对象所有属性和值的方法实现步骤1. 使用vars()和pprint()2. 使

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基