python
python练习一
判断第几天。输入某月某日,判断这一天是一年的第几天?。
代码。
#输入某月某日,判断这一天是一年的第几天?
year=eval(input('请输入年:'))
result=False
if year<9999:
if year%100==0:
if year%400==0:
result=False
elif year%4==0:
result=True
else:
result=False
if result:
month_day_t={1:31,2:29,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
else:
month_day_t={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
month=eval(input('请输入月份:'))
day=eval(input('请输入日期:'))
if month not in month_day_t:
print('输入年份有误')
exit(1)
if day<1 or day>month_day_t[month]:
print('输入日期有误')
days=0
for i in range(1,month):
days+=month_day_t[i]
print('这个是今年的第%s天。'%((days+day)))
python练习二
通讯。新建服务器端,开放连接端口,新建客户端,并且进行通讯
Client代码。
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',8889))
while True:
info=input('???')
sk.send(bytes(info,encoding='utf-8'))
Service代码。
import socket
import threading
def read(conn):
while True:
recvice_data=conn.recv(1024)
if recvice_data:
print("接受到信息",recvice_data.decode('utf-8'))
if __name__=='__main__':
sk=socket.socket()
sk.bind(('127.0.0.1',8889))
sk.listen()
conn,addr=sk.accept()
tl=threading.Thread(target=read,args=(conn,))
tl.start()
python练习三
scrapy爬虫。自定义网络爬虫,访问下面所指定培训网站并爬取培训讲师信息:http://www.itcast.cn/channel/teacher.shtml。
3.技能要求
(1)能使用集成开发环境Pycharm创建新文件并保存该新文件;
(2)能够对网站内容进行分析;
(3)能够使用Scrapy创建爬虫项目
(4)能够使用request对象;
(5)能够编写Spider爬虫代码(爬虫命名为itcast)
(6)能够使用Scrapy执行爬虫
(7)能使用PyCharm集成环境执行相关代码。
1、新建爬虫项目
1.1、切换到项目文件下面
1.2、在Terminal使用srcapy startproject 爬虫项目名称。如:srcapy startproject Day2
1.3、在项目中spiders新建爬虫区,scrapy genspider 爬虫名称 爬虫区域。如:scrapy genspider itcast itcast.cn
1.4、配置,先确定我们需要爬虫爬的数据参数,在items.py下面配置你需要的参数。
items。
class Day2Item(scrapy.Item):
# define the fields for your item here like:
name = scrapy.Field()
title = scrapy.Field()
info = scrapy.Field()
1.5、到spiders文件下面的itcast,实现具体爬虫代码。
items。
import scrapy
from ..items import *
class ItcastSpider(scrapy.Spider):
name = 'itcast'
allowed_domains = ['itcast.cn']
start_urls = ['http://www.itcast.cn/channel/teacher.shtml']
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
items = []
for each in response.xpath("//div[@class='li_txt']"):
# 将我们得到的数据封装到一个 `ItcastItem` 对象
item = Day2Item()
# extract()方法返回的都是unicode字符串
name = each.xpath("h3/text()").extract()
title = each.xpath("h4/text()").extract()
info = each.xpath("p/text()").extract()
# xpath返回的是包含一个元素的列表
item['name'] = name[0]
item['title'] = title[0]
item['info'] = info[0]
items.append(item)
# 直接返回最后数据
return items
1.6、运行爬虫scrapy crawl 爬虫名称。如:scrapy crawl itcast。