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


Posted in Python onDecember 09, 2017

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

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

3.支持多线程

from bs4 import BeautifulSoup 
import re,requests,pymysql,threading,os,traceback 
 
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 -1 
 
class DangDangThread(threading.Thread): 
  def __init__(self,keyword): 
    threading.Thread.__init__(self) 
    self.keyword = keyword 
  def run(self): 
    print('\n提示:开始爬取当当网数据...') 
    count = 1 
   
    length = 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 += 1 
          conn.commit() 
    except: 
      pass 

class AmazonThread(threading.Thread): 
  def __init__(self,keyword): 
    threading.Thread.__init__(self) 
    self.keyword = keyword 
 
  def run(self): 
    print('\n提示:开始爬取亚马逊数据...') 
    count = 1 
    length = 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 += 1 
          conn.commit() 
    except: 
      pass 

class JDThread(threading.Thread): 
  def __init__(self,keyword): 
    threading.Thread.__init__(self) 
    self.keyword = keyword 
  def run(self): 
    print('\n提示:开始爬取京东数据...') 
    count = 1 
 
    tableName = '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 += 1 
          conn.commit() 
    except : 
      pass 
def 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爬取当当、京东、亚马逊图书信息代码实例

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

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

总结

以上就是本文关于Python爬取当当、京东、亚马逊图书信息代码实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
Python修改Excel数据的实例代码
Nov 01 Python
Python中的下划线详解
Jun 24 Python
flask-restful使用总结
Dec 04 Python
Python列表常见操作详解(获取,增加,删除,修改,排序等)
Feb 18 Python
python读取图片的方式,以及将图片以三维数组的形式输出方法
Jul 03 Python
python中的反斜杠问题深入讲解
Aug 12 Python
django实现支付宝支付实例讲解
Oct 17 Python
keras中模型训练class_weight,sample_weight区别说明
May 23 Python
Keras 加载已经训练好的模型进行预测操作
Jun 17 Python
python 如何对logging日志封装
Dec 02 Python
Pytorch GPU内存占用很高,但是利用率很低如何解决
Jun 01 Python
详解Python函数print用法
Jun 18 Python
python爬取亚马逊书籍信息代码分享
Dec 09 #Python
matplotlib在python上绘制3D散点图实例详解
Dec 09 #Python
K-近邻算法的python实现代码分享
Dec 09 #Python
Python数据可视化编程通过Matplotlib创建散点图代码示例
Dec 09 #Python
python学习之matplotlib绘制散点图实例
Dec 09 #Python
Python学习pygal绘制线图代码分享
Dec 09 #Python
Python编程pygal绘图实例之XY线
Dec 09 #Python
You might like
php at(@)符号的用法简介
2009/07/11 PHP
PHP以及MYSQL日期比较方法
2012/11/29 PHP
PHP调用全国天气预报数据接口查询天气示例
2019/02/20 PHP
JS处理VBArray的函数使用说明
2008/05/11 Javascript
基于jquery的回到页面顶部按钮
2011/06/27 Javascript
jQuery在线选座位插件seat-charts特效代码分享
2015/08/27 Javascript
教你如何终止JQUERY的$.AJAX请求
2016/02/23 Javascript
JS操作JSON方法总结(推荐)
2016/06/14 Javascript
JavaScript浮点数及运算精度调整详解
2016/10/21 Javascript
javascript创建对象的3种方法
2016/11/02 Javascript
async/await与promise(nodejs中的异步操作问题)
2017/03/03 NodeJs
vue 实现移动端键盘搜索事件监听
2019/11/06 Javascript
vue.js+element 默认提示中英文操作
2020/11/11 Javascript
vue-video-player 断点续播的实现
2021/02/01 Vue.js
python 动态获取当前运行的类名和函数名的方法
2014/04/15 Python
Python3读取文件常用方法实例分析
2015/05/22 Python
Python求两个文本文件以行为单位的交集、并集与差集的方法
2015/06/17 Python
在Mac OS上使用mod_wsgi连接Python与Apache服务器
2015/12/24 Python
python爬虫爬取淘宝商品信息
2018/02/23 Python
基于python 处理中文路径的终极解决方法
2018/04/12 Python
Python关于excel和shp的使用在matplotlib
2019/01/03 Python
使用python绘制二元函数图像的实例
2019/02/12 Python
浅谈Python基础—判断和循环
2019/03/22 Python
Python写出新冠状病毒确诊人数地图的方法
2020/02/12 Python
Python实现发票自动校核微信机器人的方法
2020/05/22 Python
五分钟学会怎么用python做一个简单的贪吃蛇
2021/01/12 Python
CSS3 RGBA色彩模式使用实例讲解
2016/04/26 HTML / CSS
HTML5 使用 sessionStorage 进行页面传值的方法
2018/07/02 HTML / CSS
奥地利网上书店:Weltbild
2017/07/14 全球购物
南京某软件公司的.net面试题
2015/11/30 面试题
普罗米修斯教学反思
2014/02/06 职场文书
留学推荐信中文范文
2015/03/26 职场文书
卢旺达饭店观后感
2015/06/05 职场文书
欢送会主持词
2015/07/01 职场文书
环保宣传语大全
2015/07/13 职场文书
高中化学教学反思
2016/02/22 职场文书