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开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑