1. 设置字符编码格式
#设定编码格式
encoding = sys.getfilesystemencoding()
#编码格式转换
html_str = html_str.decode('UTF-8').encode(encoding)
2. 查看变量类型
print type(html_str)
3. 类似set的结构
#将变量值作为dict的key,保证期唯一性;value可以为空
dict[url] = ' '
4. 读取文件
#文件读取流
f = file(path)
#读取全部内容
while True:
line = f.readline()
#如果内容读完,退出循环
if len(line) == 0:
break
print line
#关闭文件流
f.close()
5. 写文件
#文件写入流
f = file(path, 'w')
#写入文件内容
f.write('content')
#关闭文件流
f.close()
6. 变量类型转换
str = str(num)
num = int(str)
7. 保存网页图片
#链接访问
urlopen=urllib.URLopener()
fp = urlopen.open(imgUrl)
data = fp.read()
fp.close()
#输出内容
fout1 = file(fileName+'.jpeg', "wb")
fout1.write(data)
fout1 = file(fileName+'.jpeg', "wb")
fout1.write(data)
fout1.close()
8. 正则表达式
#正则格式,r表示不对字符进行转义;?表示进行的是非贪婪匹配,即找到匹配的内容即停止
biaoti_reg = r'<h1>(.*?)</h1>'
#匹配字符
biaoti = re.findall(biaoti_reg, html_str)
#获得内容
biaoti_str = biaoti[0]
9. 根据字符串索引,获得子串
#正向获得子串
html = html_str[1:3]
#逆向获得子串
html = html_str[-3,-1]