学习目标
1、random+print+while+format+判断符号>>>彩票游戏
2、open+readlines+def函数>>>卖包子
3、split+replace+readlines+sockets>>>批量获取域名对应ip并保存
案例练习
猜彩票
import random,time
a = '{}{}{}{}{}{}'.format(random.randint(1,9),random.randint(1,9),random.randint(1,9),random.randint(1,9),random.randint(1,9),random.randint(1,9))
print('本期彩票开奖号码为{}'.format(a))
time.sleep(2)
count = 1
while 1:
b = '{}{}{}{}{}{}'.format(random.randint(1,9),random.randint(1,9),random.randint(1,9),random.randint(1,9),random.randint(1,9),random.randint(1,9))
print('第{}次猜测彩票号码为{}'.format(count,b))
count += 1
if a == b:
break
print('本期彩票开奖号码为{}'.format(a))
卖包子
import random
def mbz(user):
print('用户{}买了{}个包子'.format(user,random.randint(1,50)))
with open('user.txt','r',encoding='utf-8') as a:
for i in a:
mbz(i.strip())
列表推导式
import random
def mbz(user):
print('用户{}买了{}个包子'.format(user,random.randint(1,50)))
fd = [i.strip() for i in open('user.txt','r',encoding='utf-8').readlines()]
for i in fd:
mbz(i)
域名批量转ip
了解
socket中gethostbyname是把域名转为ip的方法
import socket
def ip(url):
ip = socket.gethostbyname(url)
print(ip)
ip('www.baidu.com')
第一步:打开文件
import socket
urls = [i.strip() for i in open('url.txt','r',encoding='utf-8').readlines()]
for i in urls:
print(i)
第二步:处理域名格式
我们只需要像www.baidu.com格式的
我们要处理的是前面的http://和最后面的/
先通过split方法分割,通过://分割成两个部分,分割后再取列表后面的部分,也就是[1]
import socket
urls = [i.strip() for i in open('url.txt','r',encoding='utf-8').readlines() ]
for i in urls:
print(i.split('://')[1])
我们发现有的地址后面还有/,我们可以通过替换为空,这样我们就拿到想要的域名了
import socket
urls = [i.strip() for i in open('url.txt','r',encoding='utf-8').readlines() ]
for i in urls:
print(i.split('://')[1].replace('/',''))
第三步:转换并存储
这时候配合就可以socket就可以实现转换了
import socket
urls = [i.strip() for i in open('url.txt','r',encoding='utf-8').readlines() ]
def ip(url):
ip = socket.gethostbyname(url)
print(ip)
for i in urls:
ip(i.split('://')[1].replace('/',''))
但ip可能会重复,所以我们用集合来存
import socket
urls = [i.strip() for i in open('url.txt','r',encoding='utf-8').readlines() ]
ips = set()
def ip(url):
ip = socket.gethostbyname(url)
ips.add(ip)
for i in urls:
ip(i.split('://')[1].replace('/',''))
print(ips)
第四步:把数据存文本中
这样存储后发现数据在一行里
import socket
urls = [i.strip() for i in open('url.txt','r',encoding='utf-8').readlines() ]
ips = set()
def ip(url):
try:
ip = socket.gethostbyname(url)
ips.add(ip)
except Exception as e:
print(e)
for i in urls:
ip(i.split('://')[1].replace('/',''))
with open('ip.txt','a+',encoding='utf-8')as a:
a.writelines(ips)
可以设置集合每添加一次就换行一次,使用\n
import socket
urls = [i.strip() for i in open('url.txt','r',encoding='utf-8').readlines() ]
ips = set()
def ip(url):
try:
ip = socket.gethostbyname(url)
ips.add(ip+'\n')
except Exception as e:
print(e)
for i in urls:
ip(i.split('://')[1].replace('/',''))
with open('ip.txt','a+',encoding='utf-8')as a:
a.writelines(ips)
标签:练习,socket,python,ip,random,url,urls,print,综合
From: https://www.cnblogs.com/JFSec/p/17792526.html