一、Python基础语法
import 文件名 导入文件from tutorial.items.item import ShopItem 调用tutorial.items.item文件 的ShopItem类 类的创建class 类名 (继承类): 基础objectfor namekey, namevalue in dic.iteritems(): 遍历字典发for dec in description: 遍历数组 if a>10 or a<0: 或 if a>0 and b>0: 与 类型转化 eg: str(1) int('1') 字符串拼接 eg: str1 = 'aaa' str2 = 'bbb' str3 = str1+str2+'ccc' 类的初始化:def __init__(self, 参数1,参数2,........, *args, **kwargs): super(类名, self).__init__(*args, **kwargs) 初始化方法:type若没有被赋值,默认为0 用函数时,缺省参数的值如果没有传入,则被认为是默认值def __init__(self, type='0', url='', *args, **kwargs): super(ZapposSpiders_two, self).__init__(*args, **kwargs) 二、正则表达式: import re re.search eg:匹配url字符串 是否包含http://zappos.com/menif re.search(r"^(http://www.zappos.com/men)", url, re.M | re.I): eg: response 一块内容:var colorNames = { '3':"Black", '105':"Black Stretch", '301901':"Black Stretch 1" }; 比如匹配获取colorNames 的内容值从一个从response中正则匹配 出colorName内容 已var colorName = 开始 到已经;结尾 *若干 若没有*表示只取到var colorName = 后面一个字符colorNamesString = re.search(r'(?<=var colorNames = ){[^;]*', response.body) 若匹配到colorNameString,colorNameString是一个对象。 用colorNameString = colorNameString.group() colorNameString变成JSONstrinfo = re.compile("'") # 单引号 替换 双引号styleIdsString = strinfo.sub('"', styleIdsString.group()) 结果:{"3":"Black","105":"Black Stretch","301901":"Black Stretch 1"} eg:phone = '2004-959-559'num = re.sub(r'\D', "", phone)num结果为:2004959559
表示:从response中匹配
eg:匹配字符串为pImgs[3632062]['2x']['2'] = 'http://www.zappos.com/images/z/3/6/3/2/0/6/3632062-2-2x.jpg'; pImgs[3632062]['4x']['2'] = { filename: 'http://www.zappos.com/images/z/3/6/3/2/0/6/3632062-2-4x.jpg', width: '1920', height: '2240' }; pImgs[3632062]['MULTIVIEW_THUMBNAILS']['3'] = 'http://www.zappos.com/images/z/3/6/3/2/0/6/3632062-3-MULTIVIEW_THUMBNAILS.jpg'; pImgs[3632062]['MULTIVIEW']['3'] = 'http://www.zappos.com/images/z/3/6/3/2/0/6/3632062-3-MULTIVIEW.jpg';
[ ] ' 为特殊字符 匹配需要前面加\
\d+ \d表示匹配数字 +表示若干个 .*表示后面若干个 g表示已经g结尾 包括g \D表示非数字
比如要匹配出 第1.第2条数据
imageList = re.findall(r'pImgs\[\d+\]\[\'\d.*g',respinse.body)
若匹配出 第3.第4条数据imageList = re.findall(r'pImgs\[\d+\]\[\'\D.*g',respinse.body) 结果: pImgs[3632062]['MULTIVIEW_THUMBNAILS']['3'] = 'http://www.zappos.com/images/z/3/6/3/2/0/6/3632062-3-MULTIVIEW_THUMBNAILS.jpg pImgs[3632062]['MULTIVIEW']['3'] = 'http://www.zappos.com/images/z/3/6/3/2/0/6/3632062-3-MULTIVIEW.jpg