1.Python获取图片保存本地
#coding=utf-8
#re模块主要包含了正则表达式
import re
#Urllib模块提供了读取web页面数据的接口
import urllib
#getHtml()函数传递一个网址并把整个页面下载下来
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
#getImg()函数用于在获取的整个页面中筛选需要的图片连接并保存本地
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
x = 0
for imgurl in imglist:
urllib.urlretrieve(imgurl,'%s.jpg' % x)
x+=1
#传递的网页地址并打印输出
html = getHtml("http://tieba.baidu.com/p/2460150866")
print getImg(html)
2.Python操作mysql数据库
#coding=utf-8
import MySQLdb
#连接mysql功能
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#创建数据表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一条数据
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
#修改查询条件的数据
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
#删除查询条件的数据
#cur.execute("delete from student where age='9'")
#关闭mysql连接
cur.close()
conn.commit()
conn.close()
2.1报错ImportError: No module named MySQLdb
该错误是源于我们没有安装Python连接MySQL所需的MySQLdb库而引起
Linux Fedora, CentOS系统:yum install MySQL-python
Linux Ubuntu操作系统:apt-get install python-mysqldb
3.Python设置测试万能验证码
#coding=utf-8
import random
#生成0到10之间的随机数
#d = random.uniform(0,10)
#print d
#生成一个1000到9999之间的随机整数
d = random.randint(1000,9999)
print u"生成的随机数:%d " %d
i = input(u"请输入随机数:")
print i
if i == d:
print u"登录成功!!"
elif i == 1111:
print u"登录成功!!"
else:
print u"请重新输入验证码!"
4.Python扫描指定IP开放端口号
# -*- coding:utf8 -*-
#!/usr/bin/python
# Python: 2.7.5
# Platform: linux
# Authro: wc
# Program: port scan
# History: 2015.6.1
import socket, time, thread
socket.setdefaulttimeout(3)
def socket_port(ip,port):
"""
echo IP and port , judge port opening or closing
"""
try:
if port>=65535:
print u'scan port end'
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result=s.connect_ex((ip,port))
if result==0:
lock.acquire()
print ip,u':',port,u'port opening'
lock.release()
s.close()
except:
print u'port error'
def ip_scan(ip):
"""
echo IP , scan 0-65534 port
"""
try:
print u'start scan %s' % ip
start_time=time.time()
for i in range(0,65534):
thread.start_new_thread(socket_port,(ip,int(i)))
print u'scan end , total time : %.2f' %(time.time()-start_time)
raw_input("Press Enter to Exit")
except:
print u'scan ip error'
if __name__=='__main__':
url=raw_input('Input the ip you want to scan:\n')
lock=thread.allocate_lock()
ip_scan(url)
5.python实现简单时钟输出
import sys, signal, time
def now(): return time.ctime(time.time( ))
def onSignal(signum, stackframe):
print 'Got alarm', signum, 'at', now( )
while 1:
print 'Setting at', now( )
signal.signal(signal.SIGALRM, onSignal)
signal.alarm(5)
signal.pause( )
6.python-2.7.5集成Django-1.9
7.报错1:ImportError: No module named M2Crypto
解决1:yum install m2crypto
本文转自 guowang327 51CTO博客,原文链接:http://blog.51cto.com/guowang327/1723489,如需转载请自行联系原作者