本程序涉及以下方面知识:

1.python链接mysql数据库:http://www.cnblogs.com/miranda-tang/p/5523431.html

 

2.爬取中文网站以及各种乱码处理:http://www.cnblogs.com/miranda-tang/p/5566358.html

 

3.BeautifulSoup使用

4.原网页数据信息不全用字典的方式,把不存在的字段设置为空

详细代码:

#!/usr/bin/python
# -*- encoding:utf-8 -*-

'''
思路:
1.
从易迅网爬取冰箱的数据,包括品牌,型号,价格,容积,能效等级,制冷方式,门款式,显示方式,定频/变频,除霜模式,操作方式
2.
存入MYSQL数据库
本次限定为:
300L以上的冰箱

环境:win32 python2.7
'''

from bs4 import BeautifulSoup
import requests
import MySQLdb
import datetime
#编码
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

#连接数据库,并插入爬到的数据
def insert_db(page_list):
    try:
        #注意链接时加上charset='utf8'解决编码问题
       
conn = MySQLdb.connect(user='root', passwd='112233aa',host='192.168.1.14',db='miranda.tang',charset='utf8')
        cursor = conn.cursor()
        #删除当日已插入数据,避免重复插入
       
cursor.execute('DELETE FROM yixun_price_refrigerator
WHERE update_day=
CURRENT_DATE()')
        conn.commit()   #提交
       
#executemany一次性提交爬取数据,比直接用execute
       
sql='INSERT INTO yixun_price_refrigerator
values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
       
cursor.executemany(sql,
page_list)
        conn.commit()   #提交
       
cursor.close() #关闭cursor
       
conn.close()   #关闭连接
   
except Exception as e:
        print e
        conn.rollback()
#得到soup
def urlBS(url):
    response=requests.get(url)
    soup = BeautifulSoup(response.text,"lxml")
    return soup
#得到一共有多少页
def get_pagenumber(url):
    soup=urlBS(url)
    page=soup.select('.sort_page_num span')[0]
    page_contents=page.contents[1]
    pagenumber=int(page_contents.replace('/',''))
    return pagenumber
#得到页面信息
def get_info(product_url):
    soup=urlBS(product_url)
    # print soup
    #get title
   
title = unicode(soup.title.text.strip().strip(u'【价格_报价_图片_行情】-易迅网').replace(u'',''))\
        .encode('utf-8').decode('utf-8')
    #print title

#get_原价
   
try:
        soup_origin = soup.find("dl", { "class" : "xbase_item xprice xprice_origin" })
        price_origin = soup_origin.find("span", { "class" : "mod_price xprice_val" }).\
            contents[1].text.encode('utf-8').decode('utf-8')
       # print u'原价:' + price_origin
   
except:
        price_origin=0
        #pass

#get 现价
   
try:
        soup_sale= soup.find('dl',{'class':'xbase_item xprice'})
        price_sale = soup_sale.find("span", { "class" : "mod_price xprice_val" }).contents[1].encode('utf-8').decode('latin1')
        #print u'现价:'+ price_sale
   
except:
        price_sale=0
        #pass

#得到列名名称
   
oup_info_name=soup.find_all('td',{'class':'name'})
    # for each in
oup_info_name:
    #    
print each.contents[0].encode('utf-8').decode('utf-8')
   
name_list=[each.contents[0].encode('utf-8').decode('utf-8') for each in oup_info_name]

#得到内容
   
soup_info_desc=soup.find_all('td',{'class':'desc'})
    # for each in
soup_info_desc:
   
#prod_list=[soup_info_desc[0].contents[0].encode('utf-8').decode('latin1')]
   
prod_list=[each.contents[0].encode("utf-8").decode("utf-8") for each in soup_info_desc] #用列表生成式将原表格中的数据放入列表中
   
pro_dic={}
    pro_list=[today,product_url,title,price_origin,price_sale]
    #因为列名爬取数据中不分数据是没有的,通过字典的方式,把没有的数据记录为空
   
for i in range(len(name_list)):
       
pro_dic[name_list[i]]=prod_list[i]

name=['品牌','型号','颜色','能效等级','冰箱容积','制冷方式','门款式','重量','尺寸','制冷类型',
          '显示方式','定频/变频','除霜模式',   '冷冻室温度区间','冷藏室温度区间','冰箱冷柜机型','操作方式']

for each in name:
        try:
            each=each.encode("utf-8").decode("utf-8")
           
pro_list.append(pro_dic[each])
            # print
pro_dic[each]
       
except:
            pro_list.append('')
            # print 'null'

# print pro_list
    # print len(pro_list)
   
page_list.append(pro_list)

#得到商品页链接
def get_product_href(url):
    soup=urlBS(url)
    product_list=soup.select('#itemList .mod_goods_img a')
    # print
product_list
   
for i in range(len(product_list)):
        pro=product_list[i]
        pro_href=pro['href']
        # return pro_href
        #print pro_href
       
get_info(pro_href)

if __name__=='__main__':
    beseurl='http://searchex.yixun.com/html?path=705882t705892&attr=42515e1o2o3o4o5o6o7'
   
max_number=get_pagenumber(beseurl)
    page_list=[]
    today=datetime.date.today()     #得到当前日期,插入更新日期
   
for i in range(1,max_number+1):
    # for i in
range(1,2):
       
newurl=beseurl+'&page='+str(i)
        #print newurl
        
get_product_href(newurl)

insert_db(page_list)

print("It's all done")

#建表
# drop table yixun_price_refrigerator;
# CREATE TABLE yixun_price_refrigerator(
# update_day date                 --
更新日期
# ,product_url    VARCHAR(300)    -- 商品链接
# ,title VARCHAR(300)  -- 名称
# ,price_origin VARCHAR(100)   -- 原价
# ,price_sale VARCHAR(100) -- 现价
# ,Brands VARCHAR(100)   -- 品牌
# ,Goods_sn VARCHAR(100)   -- 型号
# ,Colour VARCHAR(100)   -- 颜色
# ,Energy_efficiency_rating VARCHAR(100)  
--
能效等级
# ,Refrigerator_volume VARCHAR(100)  
--
冰箱容积
# ,Refrigeration VARCHAR(100)   -- 制冷方式
# ,Door_style VARCHAR(100)   -- 门款式
# ,weight VARCHAR(100)   -- 重量
# ,size VARCHAR(100)   -- 尺寸
# ,Cooling_type VARCHAR(100)   -- 制冷类型
# ,Display_method VARCHAR(100)   -- 显示方式
# ,frequency VARCHAR(100)   -- 定频/变频
# ,Defrost_mode VARCHAR(100)   -- 除霜模式
# ,Freezer_temperature_range VARCHAR(100)  
--
冷冻室温度区间
# ,Save_temperature_range VARCHAR(100)  
--
冷藏室温度区间
# ,Fridge_freezer_models VARCHAR(100)  
--
冰箱冷柜机型
# ,Operation_method VARCHAR(100)  
--
操作方式
# );

结果:

python爬虫:爬取易迅网价格信息,并写入Mysql数据库的更多相关文章

  1. python爬虫--爬取某网站电影信息并写入mysql数据库

    书接上文,前文最后提到将爬取的电影信息写入数据库,以方便查看,今天就具体实现. 首先还是上代码: # -*- coding:utf-8 -*- import requests import re im ...

  2. python爬虫–爬取煎蛋网妹子图片

    前几天刚学了python网络编程,书里没什么实践项目,只好到网上找点东西做. 一直对爬虫很好奇,所以不妨从爬虫先入手吧. Python版本:3.6 这是我看的教程:Python - Jack -Cui ...

  3. Python 爬虫 爬取 煎蛋网 图片

    今天, 试着爬取了煎蛋网的图片. 用到的包: urllib.request os 分别使用几个函数,来控制下载的图片的页数,获取图片的网页,获取网页页数以及保存图片到本地.过程简单清晰明了 直接上源代 ...

  4. python爬虫爬取煎蛋网妹子图片

    import urllib.request import os def url_open(url): req = urllib.request.Request(url) req.add_header( ...

  5. 利用Python网络爬虫爬取学校官网十条标题

    利用Python网络爬虫爬取学校官网十条标题 案例代码: # __author : "J" # date : 2018-03-06 # 导入需要用到的库文件 import urll ...

  6. 用Python爬虫爬取广州大学教务系统的成绩(内网访问)

    用Python爬虫爬取广州大学教务系统的成绩(内网访问) 在进行爬取前,首先要了解: 1.什么是CSS选择器? 每一条css样式定义由两部分组成,形式如下: [code] 选择器{样式} [/code ...

  7. Python爬虫爬取全书网小说,程序源码+程序详细分析

    Python爬虫爬取全书网小说教程 第一步:打开谷歌浏览器,搜索全书网,然后再点击你想下载的小说,进入图一页面后点击F12选择Network,如果没有内容按F5刷新一下 点击Network之后出现如下 ...

  8. Python爬虫|爬取喜马拉雅音频

    "GOOD Python爬虫|爬取喜马拉雅音频 喜马拉雅是知名的专业的音频分享平台,用户规模突破4.8亿,汇集了有声小说,有声读物,儿童睡前故事,相声小品等数亿条音频,成为国内发展最快.规模 ...

  9. Python爬虫 - 爬取百度html代码前200行

    Python爬虫 - 爬取百度html代码前200行 - 改进版,  增加了对字符串的.strip()处理 源代码如下: # 改进版, 增加了 .strip()方法的使用 # coding=utf-8 ...

随机推荐

  1. BZOJ 1740: [Usaco2005 mar]Yogurt factory 奶酪工厂 贪心 + 问题转化

    Description The cows have purchased a yogurt factory that makes world-famous Yucky Yogurt. Over the ...

  2. How to use pthread_create && mutex?

    1 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread. ...

  3. [转]理解和配置 Linux 下的 OOM Killer

    最近有位 VPS 客户抱怨 MySQL 无缘无故挂掉,还有位客户抱怨 VPS 经常死机,登陆到终端看了一下,都是常见的 Out of memory 问题.这通常是因为某时刻应用程序大量请求内存导致系统 ...

  4. 洛谷P1090 合并果子【贪心】

    在一个果园里,多多已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆.多多决定把所有的果子合成一堆. 每一次合并,多多可以把两堆果子合并到一起,消耗的体力等于两堆果子的重量之和.可以看出,所 ...

  5. 08.Web服务器-3.Web静态服务器

    1.显示固定的页面 from socket import * from multiprocessing import * import os def handleClient(clientSocket ...

  6. 【习题4-1 Uva1589】Xiangqi

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 车是可以被吃掉的... 注意这个情况. 其他的模拟即可. [代码] #include <bits/stdc++.h> u ...

  7. Atomic operations on the x86 processors

    On the Intel type of x86 processors including AMD, increasingly there are more CPU cores or processo ...

  8. Leading and Trailing

    You are given two integers: n and k, your task is to find the most significant three digits, and lea ...

  9. [bzoj2131]免费的馅饼_树状数组

    免费的馅饼 bzoj-2131 题目大意: 注释:$1\le n \le 10^5$,$1\le w \le 10^8$. 想法:首先,想到dp 状态:dp[i][j]表示i分钟在位置j的最大收益 优 ...

  10. MYSQL 技术内幕 博客学习

    http://blog.csdn.net/CCyutaotao/article/category/6147849/3