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使用装饰器和线程限制函数执行时间的方法
Apr 18 Python
Python socket编程实例详解
May 27 Python
python3中str(字符串)的使用教程
Mar 23 Python
python先序遍历二叉树问题
Nov 10 Python
python 使用re.search()筛选后 选取部分结果的方法
Nov 28 Python
python爬虫超时的处理的实例
Dec 19 Python
Python常见读写文件操作实例总结【文本、json、csv、pdf等】
Apr 15 Python
python实现登录密码重置简易操作代码
Aug 14 Python
Django 项目布局方法(值得推荐)
Mar 22 Python
如何基于windows实现python定时爬虫
May 01 Python
python操作redis数据库的三种方法
Sep 10 Python
关于python tushare Tkinter构建的简单股票可视化查询系统(Beta v0.13)
Oct 19 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脚本中include文件出错解决方法
2008/11/20 PHP
php文件上传表单摘自drupal的代码
2011/02/15 PHP
php 文章调用类代码
2011/08/11 PHP
PHP取整函数:ceil,floor,round,intval的区别详细解析
2013/08/31 PHP
PHP中preg_match正则匹配中的/u、/i、/s含义
2015/04/17 PHP
php的文件上传入门教程(实例讲解)
2014/04/10 Javascript
jquery实现鼠标滑过后动态图片提示效果实例
2015/08/10 Javascript
Linux CentOS系统下安装node.js与express的方法
2017/04/01 Javascript
Node.js 8 中的重要新特性
2017/06/28 Javascript
Angular.js前台传list数组由后台spring MVC接收数组示例代码
2017/07/31 Javascript
vue2导航根据路由传值,而改变导航内容的实例
2017/11/10 Javascript
vue-resource请求实现http登录拦截或者路由拦截的方法
2018/07/11 Javascript
Vuex的基本概念、项目搭建以及入坑点
2018/11/04 Javascript
微信小程序时间标签和时间范围的联动效果
2019/02/15 Javascript
vue swipe自定义组件实现轮播效果
2019/07/03 Javascript
layui下拉列表select实现可输入查找的方法
2019/09/28 Javascript
nodejs对mongodb数据库的增加修删该查实例代码
2020/01/05 NodeJs
使用JavaScript通过前端发送电子邮件
2020/05/22 Javascript
Python模拟登录12306的方法
2014/12/30 Python
Python中用字符串调用函数或方法示例代码
2017/08/04 Python
Python中对数组集进行按行打乱shuffle的方法
2018/11/08 Python
python和js交互调用的方法
2020/06/23 Python
Python-split()函数实例用法讲解
2020/12/18 Python
利用CSS3 动画 绘画 圆形动态时钟
2018/03/20 HTML / CSS
css3 利用transform打造走动的2D时钟
2020/10/20 HTML / CSS
VisionPros美国站:加拿大在线隐形眼镜和眼镜零售商
2020/02/11 全球购物
荷兰DOD药房中文官网:DeOnlineDrogist
2020/12/27 全球购物
什么是Assembly(程序集)
2014/09/14 面试题
出纳工作岗位责任制
2014/02/02 职场文书
经理管理专业毕业自荐书范文
2014/02/12 职场文书
农村婚庆司仪主持词
2014/03/15 职场文书
春游踏青活动方案
2014/08/14 职场文书
群众路线剖析材料(四风问题)
2014/10/08 职场文书
党员廉政准则心得体会
2016/01/20 职场文书
Jackson 反序列化时实现大小写不敏感设置
2021/06/29 Java/Android
SSM项目使用拦截器实现登录验证功能
2022/01/22 Java/Android