Faker


Faker

github地址https://github.com/joke2k/faker

官方地址https://faker.readthedocs.io/en/master/

一、Faker是干什么的?

Faker是一个Python包,主要用来创建伪数据,使用Faker包,无需再手动生成或者手写随机数来生成数据,只需要调用Faker提供的方法,即可完成数据的生成

安装

from faker import Faker


faker = Faker()
print(faker.name()) # 随机生成一个英文名字
print(faker.address())

# 想要造出中文的信息,实例化Faker("zh_CN")

faker = Faker(locale="zh_CN")
print(faker.name())   # 随机一个字符串的中文名字
print(faker.address()) # 随机一个字符串的中文地址
# ssn 随机身份证号码
print(faker.ssn()) # 654225197703302254
# 随机手机号
print(faker.phone_number())
# 随机手机号段
print(faker.phonenumber_prefix())
# 随机出生日期
print(faker.date_object(end_datetime=None)) # 2003-07-16
print(faker.date_time()) # 1996-03-02 06:18:31
print(faker.bban()) # 银行卡号
print(faker.iban()) # 银行卡号
print(faker.building_number())
# 信用卡 卡号
print(faker.credit_card_number()) # 4010939064933131739
# user_agent 用户代理
print(faker.user_agent()) # Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1; Trident/5.1)
print(faker.city_suffix())
print(faker.country()) # 随机国家
print(faker.postcode()) # 邮政编码
print(faker.credit_card_full())
print(faker.credit_card_number())
# 随机指定多少位的 条形码
print(faker.ean(length=13))  # 9150809223580

import json
b = json.loads(faker.json())
print(b)
print(faker.name_female())
print(faker.name_male())
# 随机生成Chrome的浏览器user_agent信息
print(faker.chrome())
# 随机生成FireFox的浏览器user_agent信息
print(faker.firefox())
# 生成一篇文章
print(faker.text())
# 生成一个列表 文章
print(faker.texts())
#随机md5
print(faker.md5())

print(faker.safe_email())
print(faker.email())
print(faker.ipv4())
# 个人IP地址
print(faker.ipv4_private())
print(faker.url())
print(faker.word())
print(faker.password(special_chars=False))



方法真尼玛太多了,而且还不知道具体方法到底是什么意思。所以在下面我用dir()方法统计几乎99%的方法然后写入到一个文件。看作文意思几乎能知道具体那个方法,具体是干什么用的。

faker所有方法调用:格式faker.方法()

a = ['address', 'am_pm', 'android_platform_token', 'ascii_company_email', 'ascii_email', 'ascii_free_email', 'ascii_safe_email', 'bank_country', 'bban', 'boolean', 'bothify', 'bs', 'building_number', 'cache_pattern', 'catch_phrase', 'century', 'chrome', 'city', 'city_name', 'city_suffix', 'color', 'color_name', 'company', 'company_email', 'company_prefix', 'company_suffix', 'coordinate', 'country', 'country_calling_code', 'country_code', 'credit_card_expire', 'credit_card_full', 'credit_card_number', 'credit_card_provider', 'credit_card_security_code', 'cryptocurrency', 'cryptocurrency_code', 'cryptocurrency_name', 'csv', 'currency', 'currency_code', 'currency_name', 'currency_symbol', 'date', 'date_between', 'date_between_dates', 'date_object', 'date_of_birth', 'date_this_century', 'date_this_decade', 'date_this_month', 'date_this_year', 'date_time', 'date_time_ad', 'date_time_between', 'date_time_between_dates', 'date_time_this_century', 'date_time_this_decade', 'date_time_this_month', 'date_time_this_year', 'day_of_month', 'day_of_week', 'del_arguments', 'dga', 'district', 'domain_name', 'domain_word', 'dsv', 'ean', 'ean13', 'ean8', 'email', 'factories', 'file_extension', 'file_name', 'file_path', 'firefox', 'first_name', 'first_name_female', 'first_name_male', 'first_name_nonbinary', 'first_romanized_name', 'fixed_width', 'format', 'free_email', 'free_email_domain', 'future_date', 'future_datetime', 'generator_attrs', 'get_arguments', 'get_formatter', 'hex_color', 'hexify', 'hostname', 'http_method', 'iban', 'image_url', 'internet_explorer', 'ios_platform_token', 'ipv4', 'ipv4_network_class', 'ipv4_private', 'ipv4_public', 'ipv6', 'isbn10', 'isbn13', 'iso8601', 'items', 'job', 'json', 'language_code', 'language_name', 'last_name', 'last_name_female', 'last_name_male', 'last_name_nonbinary', 'last_romanized_name', 'latitude', 'latlng', 'lexify', 'license_plate', 'linux_platform_token', 'linux_processor', 'local_latlng', 'locale', 'locales', 'localized_ean', 'localized_ean13', 'localized_ean8', 'location_on_land', 'longitude', 'mac_address', 'mac_platform_token', 'mac_processor', 'md5', 'mime_type', 'month', 'month_name', 'msisdn', 'name', 'name_female', 'name_male', 'name_nonbinary', 'null_boolean', 'numerify', 'opera', 'paragraph', 'paragraphs', 'parse', 'password', 'past_date', 'past_datetime', 'phone_number', 'phonenumber_prefix', 'port_number', 'postcode', 'prefix', 'prefix_female', 'prefix_male', 'prefix_nonbinary', 'profile', 'provider', 'providers', 'province', 'psv', 'pybool', 'pydecimal', 'pydict', 'pyfloat', 'pyint', 'pyiterable', 'pylist', 'pyset', 'pystr', 'pystr_format', 'pystruct', 'pytimezone', 'pytuple', 'random', 'random_choices', 'random_digit', 'random_digit_not_null', 'random_digit_not_null_or_empty', 'random_digit_or_empty', 'random_element', 'random_elements', 'random_int', 'random_letter', 'random_letters', 'random_lowercase_letter', 'random_number', 'random_sample', 'random_uppercase_letter', 'randomize_nb_elements', 'rgb_color', 'rgb_css_color', 'romanized_name', 'safari', 'safe_color_name', 'safe_domain_name', 'safe_email', 'safe_hex_color', 'seed', 'seed_instance', 'seed_locale', 'sentence', 'sentences', 'set_arguments', 'set_formatter', 'sha1', 'sha256', 'simple_profile', 'slug', 'ssn', 'street_address', 'street_name', 'street_suffix', 'suffix', 'suffix_female', 'suffix_male', 'suffix_nonbinary', 'swift', 'swift11', 'swift8', 'text', 'texts', 'time', 'time_delta', 'time_object', 'time_series', 'timezone', 'tld', 'tsv', 'unix_device', 'unix_partition', 'unix_time', 'upc_a', 'upc_e', 'uri', 'uri_extension', 'uri_page', 'uri_path', 'url', 'user_agent', 'user_name', 'uuid4', 'weights', 'windows_platform_token', 'word', 'words', 'year']
# 将方法写入到一个文件,方便以后查看。百度好多都不是faker最新版本的,参考价值大打折扣。
f = open("faker.txt","wt",encoding="utf-8")

for i in a:
    try:

        exec(f"print('{i}-->' ,faker."+f"{i}(),file=f)")
    except Exception as e:
        continue

f.close()

三、常用函数

1、地理信息类

  • fake.city_suffix():市,县
  • fake.country():国家
  • fake.country_code():国家编码
  • fake.district():区
  • fake.geo_coordinate():地理坐标
  • fake.latitude():地理坐标(纬度)
  • fake.longitude():地理坐标(经度)
  • fake.postcode():邮编
  • fake.province():省份
  • fake.address():详细地址
  • fake.street_address():街道地址
  • fake.street_name():街道名
  • fake.street_suffix():街、路

2、基础信息类

  • ssn():生成身份证号
  • bs():随机公司服务名
  • company():随机公司名(长)
  • company_prefix():随机公司名(短)
  • company_suffix():公司性质
  • credit_card_expire():随机信用卡到期日
  • credit_card_full():生成完整信用卡信息
  • credit_card_number():信用卡号
  • credit_card_provider():信用卡类型
  • credit_card_security_code():信用卡安全码
  • job():随机职位
  • first_name_female():女性名
  • first_name_male():男性名
  • last_name_female():女姓
  • last_name_male():男姓
  • name():随机生成全名
  • name_female():男性全名
  • name_male():女性全名
  • phone_number():随机生成手机号
  • phonenumber_prefix():随机生成手机号段

3、计算机基础、Internet信息类

  • ascii_company_email():随机ASCII公司邮箱名
  • ascii_email():随机ASCII邮箱:
  • company_email():
  • email():
  • safe_email():安全邮箱

4、网络基础信息类

  • domain_name():生成域名
  • domain_word():域词(即,不包含后缀)
  • ipv4():随机IP4地址
  • ipv6():随机IP6地址
  • mac_address():随机MAC地址
  • tld():网址域名后缀(.com,.net.cn,等等,不包括.)
  • uri():随机URI地址
  • uri_extension():网址文件后缀
  • uri_page():网址文件(不包含后缀)
  • uri_path():网址文件路径(不包含文件名)
  • url():随机URL地址
  • user_name():随机用户名
  • image_url():随机URL地址

5、浏览器信息类

  • chrome():随机生成Chrome的浏览器user_agent信息
  • firefox():随机生成FireFox的浏览器user_agent信息
  • internet_explorer():随机生成IE的浏览器user_agent信息
  • opera():随机生成Opera的浏览器user_agent信息
  • safari():随机生成Safari的浏览器user_agent信息
  • linux_platform_token():随机Linux信息
  • user_agent():随机user_agent信息

6、数字类

  • numerify():三位随机数字

  • random_digit():0~9随机数

  • random_digit_not_null():1~9的随机数

  • random_int():随机数字,默认0~9999,可以通过设置min,max来设置

  • random_number():随机数字,参数digits设置生成的数字位数

  • pyfloat():

    left_digits=5 #生成的整数位数, right_digits=2 #生成的小数位数, positive=True #是否只有正数

  • pyint():随机Int数字(参考random_int()参数)

  • pydecimal():随机Decimal数字(参考pyfloat参数)

7、文本、加密类

  • pystr():随机字符串
  • random_element():随机字母
  • random_letter():随机字母
  • paragraph():随机生成一个段落
  • paragraphs():随机生成多个段落
  • sentence():随机生成一句话
  • sentences():随机生成多句话,与段落类似
  • text():随机生成一篇文章
  • word():随机生成词语
  • words():随机生成多个词语,用法与段落,句子,类似
  • binary():随机生成二进制编码
  • boolean():True/False
  • language_code():随机生成两位语言编码
  • locale():随机生成语言/国际 信息
  • md5():随机生成MD5
  • null_boolean():NULL/True/False
  • password():随机生成密码,可选参数:length:密码长度;special_chars:是否能使用特殊字符;digits:是否包含数字;upper_case:是否包含大写字母;lower_case:是否包含小写字母
  • sha1():随机SHA1
  • sha256():随机SHA256
  • uuid4():随机UUID

8、时间信息类

  • date():随机日期
  • date_between():随机生成指定范围内日期,参数:start_date,end_date
  • date_between_dates():随机生成指定范围内日期,用法同上
  • date_object():随机生产从1970-1-1到指定日期的随机日期。
  • date_time():随机生成指定时间(1970年1月1日至今)
  • date_time_ad():生成公元1年到现在的随机时间
  • date_time_between():用法同dates
  • future_date():未来日期
  • future_datetime():未来时间
  • month():随机月份
  • month_name():随机月份(英文)
  • past_date():随机生成已经过去的日期
  • past_datetime():随机生成已经过去的时间
  • time():随机24小时时间
  • timedelta():随机获取时间差
  • time_object():随机24小时时间,time对象
  • time_series():随机TimeSeries对象
  • timezone():随机时区
  • unix_time():随机Unix时间
  • year():随机年份

9、python 相关方法

  • profile():随机生成档案信息
  • simple_profile():随机生成简单档案信息
  • pyiterable()
  • pylist()
  • pyset()
  • pystruct()
  • pytuple()
  • pydict()

可以用dir(fake),看Faker库都可以fake哪些数据,目前Faker支持近300种数据,此外还支持自己进行扩展。

有了这些生成数据函数之后用fake对象就可以调用不同的方法生成各种数据了。

3.1 常用数据场景

1、构造通讯录记录

from faker import Faker

fake = Faker(locale='zh_CN')
print('Card Number:', fake.credit_card_number(card_type=None))
print('Card Provider:', fake.credit_card_provider(card_type=None))
print('Card Security Code:', fake.credit_card_security_code(card_type=None))
print('Card Expire:', fake.credit_card_expire())

# 输出信息:
Card Number: 676181530350
Card Provider: Diners Club / Carte Blanche
Card Security Code: 615
Card Expire: 09/21

3、生成个人档案信息

from faker import Faker

fake = Faker(locale='zh_CN')
print('生成Python字典: {}'.format(fake.pydict(
    nb_elements=10, variable_nb_elements=True)))  # Python字典
print('生成Python可迭代对象:{}.'.format(fake.pyiterable(
    nb_elements=10, variable_nb_elements=True)))   # Python可迭代对象
print('生成Python结构:{}'.format(fake.pystruct(count=1)))  # Python结构


# 输出信息
成Python字典: {'论坛': 'nVcSbHlrcrhIBtwByVUM', '直接': 'drkyFUNcNxdbwYKhRLEZ', '成功': 'https://fang.cn/main/search/blog/search/', '没有': datetime.datetime(2006, 2, 24, 15, 40, 14), '原因': 404, '作者': 'OTJjsFHQklpUvTPtLCqP'}
生成Python可迭代对象:{1088, 'ignqbohwYRxqolLEzSti', 'http://gang.cn/main/search.php', 'zRnNYdIpPXUxEVISHbvS', 'ToZxuBetghvlPHUumAvi', 9830, 'OYAjoKeVNGhHMLgnYUAw', 970446.888, -17681479853.4069, 872236250787063.0, datetime.datetime(2017, 12, 24, 5, 58, 58), 'aRSfxiUSuMqHXvKCCkMJ'}
生成Python结构:(['cKwOvdCEFOhCERMSMXSf'], {'只有': 'hhwGCmjkHMOUjBTDztXp'}, {'还有': {0: 'vjcNqpnRbNUUxXpgVyvh', 1: [8725, 7125, 'aTSJssAJUKpuRLcbiwyK'], 2: {0: 'RmWlFQQpVZIQkxZPfJnq', 1: 'efsUVLgeStXbCOJDuJCf', 2: ['FgZQLCRjUTmEbBdDMEPZ', 'https://min.cn/search/faq/']}}})

四、 自定义Faker数据类型

如果这些数据还不够生成数据使用,Faker还支持创建自定义的Provider生成数据。

faker:
https://zhuanlan.zhihu.com/p/87203290
https://blog.csdn.net/qq_41703291/article/details/87898556

https://mp.weixin.qq.com/s?__biz=MzA4NDUyNzA0Ng==&mid=2247486145&idx=1&sn=4d309ad345174c63c9855501ae10c883&chksm=9fe49868a893117e917b241df9883c9b2c11374457162d88beba49960ced833a8a89d7ca1784&mpshare=1&scene=1&srcid=0707Uho3BpFNA7wpORVmLl2y&sharer_sharetime=1598445800326&sharer_shareid=a7e895789819ce3b0777e7e2dba37550&key=e0a4d01c3985cc28d44c99e2e1da7f6cf94cde3d944a213ec313d8eb6d6a2504160ccfe261f820eadb8d4ebd2065f8e4582ef6a4e8a4b7a21f28c96e5556b4cc3307e56261805dc8b9f24fb7990a74eb5882b76c28576b481c598b2d3718084e6812ef56b5e502609d25e80545aede16589c61a8174d26a891c7cf284c534aa3&ascene=1&uin=MTIyNzc5NzY1Mg%3D%3D&devicetype=Windows+7+x64&version=62090529&lang=zh_CN&exportkey=A%2BGTpfbc6JxYXZP6vf%2F6V6A%3D&pass_ticket=Cor%2FckmqWbki0zJJ%2F8yTTjU9xjnRRnK6O4hiU56wSAIAgzIRQVpcbmm75R%2Fdn1%2Bu

https://www.cnblogs.com/python666666/p/9980243.html