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

相关文章

uniapp接入微信小程序原生代码配置方案(优化版)

uniapp项目需要把微信小程序原生语法的功能代码嵌套过来,无需把原生代码转换为uniapp,可以配置拷贝的方式集成过来 1、拷贝代码包到src目录 2、vue.config.js中配置原生代码包直接拷贝到编译目录中 3、pages.json中配置分包目录,原生入口组件的路径 4、manifest.json中配置分包,使用原生组件 5、需要把原生代码包里的页面修改成组件的方

swiper实例

大家好,我是燐子,今天给大家带来swiper实例   微信小程序中的 swiper 组件是一种用于创建滑动视图的容器组件,常用于实现图片轮播、广告展示等效果。它通过一系列的子组件 swiper-item 来定义滑动视图的每一个页面。 基本用法   以下是一个简单的 swiper 示例代码:   WXML(页面结构) <swiper autoplay="true" interval="3

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus

公共筛选组件(二次封装antd)支持代码提示

如果项目是基于antd组件库为基础搭建,可使用此公共筛选组件 使用到的库 npm i antdnpm i lodash-esnpm i @types/lodash-es -D /components/CommonSearch index.tsx import React from 'react';import { Button, Card, Form } from 'antd'

17.用300行代码手写初体验Spring V1.0版本

1.1.课程目标 1、了解看源码最有效的方式,先猜测后验证,不要一开始就去调试代码。 2、浓缩就是精华,用 300行最简洁的代码 提炼Spring的基本设计思想。 3、掌握Spring框架的基本脉络。 1.2.内容定位 1、 具有1年以上的SpringMVC使用经验。 2、 希望深入了解Spring源码的人群,对 Spring有一个整体的宏观感受。 3、 全程手写实现SpringM

Python 字符串占位

在Python中,可以使用字符串的格式化方法来实现字符串的占位。常见的方法有百分号操作符 % 以及 str.format() 方法 百分号操作符 % name = "张三"age = 20message = "我叫%s,今年%d岁。" % (name, age)print(message) # 我叫张三,今年20岁。 str.format() 方法 name = "张三"age

通过高德api查询所有店铺地址信息

通过高德api查询所有店铺地址电话信息 需求:通过高德api查询所有店铺地址信息需求分析具体实现1、申请高德appkey2、下载types city 字典值3、具体代码调用 需求:通过高德api查询所有店铺地址信息 需求分析 查询现有高德api发现现有接口关键字搜索API服务地址: https://developer.amap.com/api/webservice/gui

代码随想录算法训练营:12/60

非科班学习算法day12 | LeetCode150:逆波兰表达式 ,Leetcode239: 滑动窗口最大值  目录 介绍 一、基础概念补充: 1.c++字符串转为数字 1. std::stoi, std::stol, std::stoll, std::stoul, std::stoull(最常用) 2. std::stringstream 3. std::atoi, std

记录AS混淆代码模板

开启混淆得先在build.gradle文件中把 minifyEnabled false改成true,以及shrinkResources true//去除无用的resource文件 这些是写在proguard-rules.pro文件内的 指定代码的压缩级别 -optimizationpasses 5 包明不混合大小写 -dontusemixedcaseclassnames 不去忽略非公共

一道经典Python程序样例带你飞速掌握Python的字典和列表

Python中的列表(list)和字典(dict)是两种常用的数据结构,它们在数据组织和存储方面有很大的不同。 列表(List) 列表是Python中的一种有序集合,可以随时添加和删除其中的元素。列表中的元素可以是任何数据类型,包括数字、字符串、其他列表等。列表使用方括号[]表示,元素之间用逗号,分隔。 定义和使用 # 定义一个列表 fruits = ['apple', 'banana