python_爬虫

http://study.163.com/course/courseMain.htm?courseId=1003666043

菜鸟教程:http://www.runoob.com/python/python-built-in-functions.html

python基础

并且结束的时候不需要分号结尾

中文编码

#!/usr/bin/python
# -*- coding: UTF-8 -*-   识别中文

if语句

# -*- coding: UTF-8 -*- 
if a==b:
    print "当前数字:"10
elseprint a

    #代表注释,

循环语句for while do while中的break continue pass

break  结束循环体的执行不执行以下的循环
continue 仅停止当前循环,继续执行下面的循环
pass 空语句,为了保持结构的完整性

字符串

#!/usr/bin/python

var1 = 'Hello World!'
var2 = "Python Runoob"

print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

输出

var1[0]: H
var2[0]: ytho

list

list=[1,2,3,4,5,6]
print list[1:5]

输出:
2345

添加

list=[1,2,3,4,5,6]
list.append("a")
print list

输出
123456,”a“

元组

tup1=()
元组中只包含一个元素时,需要在元素后面添加逗号

tup1 = (50,);

字典 类比于json对象

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];

时间戳

时间戳单位最适于做日期运算。但是1970年之前的日期就无法以此表示了。太遥远的日期也不行,UNIX和Windows只支持到2038年。
import time    #引入time 模块

time=time.time()
print "当前时间戳:",time
import time

localtime = time.asctime( time.localtime(time.time()) )
print "本地时间为 :", localtime

 Tue Mar 27 16:47:26 2018
格式化时间

time。strftime()

import time

# 格式化成2016-03-20 11:45:39形式
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 

定义与调用函数

def test(str):
    print str
    return

test("测试函数")

函数中return表示推出函数,不带参数值的return语句返回None

变量作用域

全局作用域,局部作用域

#!/usr/bin/python
# -*- coding: UTF-8 -*-

total = 0; # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
   #返回2个参数的和."
   total = arg1 + arg2; # total在这里是局部变量.
   print "函数内是局部变量 : ", total
   return total;

#调用sum函数
sum( 10, 20 );
print "函数外是全局变量 : ", total 

模块

定义一个sup.py文件

def support(str):
    print str
    return

写一个index.py

import sup

sup.support("test")

读取键盘输入

raw_input

input

两个函数功能类似,但是input可接受一个python表达式

str = input("请输入:")
print "你输入的内容是: ", str

请输入:[x*5 for x in range(2,10,2)]
你输入的内容是:  [10, 20, 30, 40]

file对象的属性

file.closed返回true如果文件已被关闭,否则返回false。
file.mode返回被打开文件的访问模式。
file.name返回文件的名称。
file.softspace如果用print输出后,必须跟一个空格符,则返回false。否则返回true。

方法

open()  close()  write()  read()
重命名rename() os.rename(current_file_name, new_file_name)
删除文件 remove() os.remove(file_name)

可以使用os模块的mkdir()方法在当前目录下创建新的目录们。你需要提供一个包含了要创建的目录名称的参数。

语法:

os.mkdir("newdir")
移除目录
os.rmdir('dirname')

创建实例对象

实例化类其他编程语言中一般用关键字 new,但是在 Python 中并没有这个关键字,类的实例化类似函数调用方式.通过 init 方法接收参数。

class创建一个新的类

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Employee:
   '所有员工的基类'
   empCount = 0

   def __init__(self, name, salary):    #属性
      self.name = name
      self.salary = salary
      Employee.empCount += 1

   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary
类的继承
#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Parent:        # 定义父类
   parentAttr = 100
   def __init__(self):
      print "调用父类构造函数"

   def parentMethod(self):
      print '调用父类方法'

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print "父类属性 :", Parent.parentAttr

class Child(Parent): # 定义子类
   def __init__(self):
      print "调用子类构造方法"

   def childMethod(self):
      print '调用子类方法'

c = Child()          # 实例化子类
c.childMethod()      # 调用子类的方法
c.parentMethod()     # 调用父类方法
c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
c.getAttr()          # 再次调用父类的方法 - 获取属性值
#可继承多个

class A:        # 定义类 A
.....

class B:         # 定义类 B
.....

class C(A, B):   # 继承类 A 和 B

类的属性和方法

类的私有属性
__private      双下滑线代表私有属性,不可以再类的外部访问的到

类的方法
在类的内部 def可以定义一个方法,但必须包含self且为第一个参数

类的私有方法
__methods    双下划线代表私有方法

单下划线 一般是系统定义的特殊方法 _ init() _

双下划线代表私有

正则表达式

Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。

re 模块使 Python 语言拥有全部的正则表达式功能。

re.match
re.match(pattern, string, flags=0)

匹配成功re.match方法返回一个匹配的对象,否则返回None
参数描述
pattern匹配的正则表达式
string要匹配的字符串。
flags标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志

python连接数据库

安装mysqldb的时候报错

Python version 2.7 required, which was not found in the registry

主要是安装了64位的python,但是安装的mysqldb是32位的

重新下载64位就好了

数据库语言

查询

import MySQLdb
print("hello")
db = MySQLdb.connect("localhost", "root", "", "python")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
sql="""select * from employee"""
cursor.execute(sql)
res = cursor.fetchall()
try:
    for r in res:
        a = r[0]
        b = r[1]
        c = r[2]
        d = r[3]
        e = r[4]

        print r
except:
    print("error")
# 关闭数据库连接
db.close()

修改

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# 使用cursor()方法获取操作游标 
cursor = db.cursor()

# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()                 //需要提交到数据库执行
except:
   # 发生错误时回滚
   db.rollback()

# 关闭数据库连接
db.close()

删除

!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# 使用cursor()方法获取操作游标 
cursor = db.cursor()

# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交修改
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()

# 关闭连接
db.close()

scrapy

没各项目可以有多个爬虫

1.安装python2x 配置环境变量

2.安装pip模块 配置环境变量

pip install Scrapy   //安装Scrapy
scrapy startproject pruduct  //创建scrapy项目
scrapy genspider 文件名 ‘爬取的网址’   //创建爬虫文件
scrapy crawl 爬虫名称    //运行爬虫

Scrapy运行ImportError: No module named win32api错误

windows系统上出现这个问题的解决需要安装Py32Win模块,但是直接通过官网链接装exe会出现几百个错误,更方便的做法是

pip install pypiwin32

使用python处理文件

with open as

        with open("index.html", "w") as f:    //w   打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
            f.write(response.text)

xpath

extract() 将xpath对象转化为unicode字符串

在pycharm中同级目录下的自定义模块,pycharm会报错

pycharm不会将当前文件目录自动加入自己的sourse_path。右键make_directory as-->sources path将当前工作的文件夹加入source_path就可以了。

这里写图片描述

scrapy处理图片

imagesPipeline

pipeline.py

class Tencent(imagesPipeline):
    def press_item(self,item,spider)
        return item
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐