引言:
自动化脚本编写时,一般会遇到需要构造数据的情况,比如注册时的基本信息;每次执行脚本都要重新构造数据显然是很费时费力的事情,所以可以用到faker模块来构造;方便快捷,神器也;
一、安装
pip install -U faker
二、基本用法
1.创建10次不同的用户名:
from faker import Factory def create_names(): fake = Factory.create() ): print fake.name() if __name__ == '__main__': create_names()
随机产生10个符合命名规则的假数据,因为名字规则是按外国人名涉及的,所以可能会有很多概率出现姓名之外的简称等
>>> ============== RESTART: C:\Users\hao\Desktop\faker_test.py ============== David MartinMrs. Terese Walter MDJess MayertMs. Katerina Fisher PhDMrs. Senora Purdy PhDGretchen TrompWinnie GoodwinYuridia McGlynn MDMelissa Kent April Washington >>>
2.生成只有姓和名的数据
from faker import Factory def create_names(): fake = Factory.create() ): print '%s %s' % (fake.last_name(), fake.first_name()) if __name__ == '__main__': create_names()
生成的数据只包含了last_name和first_name
>>> ============== RESTART: C:\Users\lizihao\Desktop\faker_test.py ============== Gillespie Travis Gomez Brandon Wiley Jim Anderson Amber Walker Desiree Miranda Elizabeth Johnson Samantha Tanner David Keller Allison Sanchez Kaylee >>>
3.还有一些常用的数据,比如用户名、密码、电话、住址、城市等等
from faker import Factory def create_fake_stuff(): stuff = ['user_name', 'password', 'email', 'phone_number', 'address', 'city', 'state', 'paragraph'] fake = Factory.create() for item in stuff: print '%s = %s' % (item, getattr(fake, item)()) if __name__ == '__main__': create_fake_stuff()
生成的对应的数据:
>>> ============== RESTART: C:\Users\lizihao\Desktop\faker_test.py ============== user_name = kevin04 password = PN5xUyd5n$ email = [email protected] phone_number = -- address = Brett Glens Port Jeffrey, MD city = Meltonbury state = Arizona paragraph = Iure odit voluptatibus quidem iste. Omnis ab ab voluptas consequuntur earum repellendus corrupti. >>>
三、其余的用法
如果想知道faker都能生成哪些规则的数据,可以创建fake对象,然后dir(fake);
>>> from faker import Factory >>> fake = Factory.create() >>> dir(fake) >>>
得到的结果是:
需要什么样的数据就在里面找吧,一般都能满足你的需要;