• python2.7 爬虫_爬取小说盗墓笔记章节及URL并导入MySQL数据库_20161201


    1、爬取页面 http://www.quanshu.net/book/9/9055/

    2、用到模块urllib(网页下载),re正则匹配取得title及titleurl,urlparse(拼接完整url),MySQLdb(导入MySQL) 数据库

    3、for 循环遍历列表 取得盗墓笔记章节title 和 titleurl

    4、try except 异常处理

    5、python 代码

    #-*-coding: utf-8 -*-
    import urllib
    import re
    import urlparse
    import MySQLdb
    rooturl='http://www.quanshu.net/book/9/9055/'
    #getlist返回包含title 和titleurl的列表
    def getlist(url):
        html=urllib.urlopen(url).read()
        html=html.decode('gb2312').encode('utf-8')
        reg=r'<li><a href="(.*?)" title=".*?">(.*?)</a></li>'
        return re.findall(reg,html)
    try:
        conn = MySQLdb.connect(host='localhost', user='root', passwd='Admin@', db='local_db', port=3306, charset='utf8')
        with conn:
            cursor = conn.cursor()
            #如果存在daomubiji数据表先删除
            drop_table_sql='DROP  TABLE IF EXISTS daomubiji'
            cursor.execute(drop_table_sql)
            conn.commit()
            #如果存在daomubiji数据表 先删除后接着创建daomubiji表 
            create_table_sql = '''
               CREATE TABLE daomubiji (
               ID INT(11),
               title VARCHAR(255),
               titleurl VARCHAR(255)
               )ENGINE=INNODB DEFAULT CHARSET=utf8
            '''
            cursor.execute(create_table_sql)
            conn.commit()
            #下面调用getlist()函数获取rooturl下所有章节的titleurl 和title 组成的列表
            urllist = getlist(rooturl)
            #href属性取得的url不完整 仅取出了完整url的右半段 因此下面for循环变量名起名righturl
            ID=0
            #对列表进行遍历 取 titleurl 和title
            for righturl in urllist:
                title = righturl[1]
                newurl = righturl[0]
                #urlparse 模块的urlparse.urljoin方法将righturl 按照rooturl格式拼接成完整url
                titleurl = urlparse.urljoin(rooturl, newurl)
                ID+=1
                print ID,title, titleurl
                cursor.execute("INSERT INTO  daomubiji values(%s,%s,%s)", (ID,title, titleurl))
                conn.commit()
            print "输入了"+ str(ID) +"条数据"
    except MySQLdb.Error:
        print "连接失败!"
    

      

    
    

    代码执行情况:

    6、MySQL数据库查询是否导入成功

    SELECT * FROM daomubiji
    

      

     7、执行成功

  • 相关阅读:
    bzoj4152 [AMPPZ2014]The Captain
    bzoj2429 [HAOI2006]聪明的猴子
    bzoj1196 [HNOI2006]公路修建问题
    bzoj1083 [SCOI2005]繁忙的都市
    bzoj1050 [HAOI2006]旅行comf
    bzoj1088 [SCOI2005]扫雷Mine
    bzoj1085 [SCOI2005]骑士精神
    bzoj3437 小P的牧场
    bzoj1296 [SCOI2009]粉刷匠
    A1046 Shortest Distance (20)(20 分)
  • 原文地址:https://www.cnblogs.com/Mr-Cxy/p/6124206.html
Copyright © 2020-2023  润新知