美文网首页
Python 代码片段

Python 代码片段

作者: 九命丿相柳 | 来源:发表于2017-07-24 21:11 被阅读0次

    从文件获得cookies

    cookies={}
    with open(r'cookies.txt','r') as f:
        for line in f.read().split(';'): 
        #其设置为1就会把字符串拆分成2份 
            name,value = line.strip().split('=', 1) 
            cookies[name] = value
    

    爬取网页上的图片

    import urllib.request
    import re
    def getHtml(url):
        page = urllib.request.urlopen(url)
        html = page.read().decode('utf-8')
        return html
    def getImg(html):
        reg = r'src="(.+?\.jpg)" width'
        imgre = re.compile(reg)
        imglist = re.findall(imgre,html)
        x = 0
        for imgurl in imglist:
            urllib.request.urlretrieve(imgurl,'images/%s.jpg' % x)
            x+=1
    html = getHtml('http://tieba.baidu.com/p/741081023')
    getImg(html)
    

    使用pymysql操纵MySQL

    import pymysql
    try:
        conn= pymysql.connect(host='localhost', port=3306, user='DBSAdmin', passwd='admin', charset='UTF8', db='dbs')
        cur=conn.cursor()                              #获取一个游标对象
        cur.execute("INSERT INTO nameage VALUES('小明', 15),('小洪', 17),('小高', 16),('小刚', 15)")#插入数据
        cur.execute("SELECT * FROM nameage")
        data=cur.fetchall()
        for row in data:
            print('%s\t%s' %row)
    except Exception as e:
        print("发生异常")
    finally:
        cur.close()                                    #关闭游标
        conn.commit()                                  #向数据库中提交任何未解决的事务,对不支持事务的数据库不进行任何操作
        conn.close()                                   #关闭到数据库的连接,释放数据库资源
    

    相关文章

      网友评论

          本文标题:Python 代码片段

          本文链接:https://www.haomeiwen.com/subject/svkikxtx.html