当前位置: 首页 > news >正文

盘锦威旺做网站建设发布推广信息的网站

盘锦威旺做网站建设,发布推广信息的网站,网页版游戏大全,今日头条最新新闻消息1、日期生成 很多时候我们需要批量生成日期,方法有很多,这里分享两段代码 获取过去 N 天的日期: import datetimedef get_nday_list(n):before_n_days []for i in range(1, n 1)[::-1]:before_n_days.append(str(datetime.date.today() …

1、日期生成

很多时候我们需要批量生成日期,方法有很多,这里分享两段代码

获取过去 N 天的日期:

import datetimedef get_nday_list(n):before_n_days = []for i in range(1, n + 1)[::-1]:before_n_days.append(str(datetime.date.today() - datetime.timedelta(days=i)))return before_n_daysa = get_nday_list(30)
print(a)

输出:

['2021-12-23', '2021-12-24', '2021-12-25', '2021-12-26', '2021-12-27', '2021-12-28', '2021-12-29', '2021-12-30', '2021-12-31', '2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06', '2022-01-07', '2022-01-08', '2022-01-09', '2022-01-10', '2022-01-11', '2022-01-12', '2022-01-13', '2022-01-14', '2022-01-15', '2022-01-16', '2022-01-17', '2022-01-18', '2022-01-19', '2022-01-20', '2022-01-21']

生成一段时间区间内的日期:

import datetimedef create_assist_date(datestart = None,dateend = None):# 创建日期辅助表if datestart is None:datestart = '2016-01-01'if dateend is None:dateend = datetime.datetime.now().strftime('%Y-%m-%d')# 转为日期格式datestart=datetime.datetime.strptime(datestart,'%Y-%m-%d')dateend=datetime.datetime.strptime(dateend,'%Y-%m-%d')date_list = []date_list.append(datestart.strftime('%Y-%m-%d'))while datestart<dateend:# 日期叠加一天datestart+=datetime.timedelta(days=+1)# 日期转字符串存入列表date_list.append(datestart.strftime('%Y-%m-%d'))return date_listd_list = create_assist_date(datestart='2021-12-27', dateend='2021-12-30')
d_list

输出:

['2021-12-27', '2021-12-28', '2021-12-29', '2021-12-30']

2、保存数据到CSV

保存数据到 CSV 是太常见的操作了

def save_data(data, date):if not os.path.exists(r'2021_data_%s.csv' % date):with open("2021_data_%s.csv" % date, "a+", encoding='utf-8') as f:f.write("标题,热度,时间,url\n")for i in data:title = i["title"]extra = i["extra"]time = i['time']url = i["url"]row = '{},{},{},{}'.format(title,extra,time,url)f.write(row)f.write('\n')else:with open("2021_data_%s.csv" % date, "a+", encoding='utf-8') as f:for i in data:title = i["title"]extra = i["extra"]time = i['time']url = i["url"]row = '{},{},{},{}'.format(title,extra,time,url)f.write(row)f.write('\n')

3、带背景颜色的 Pyecharts

Pyecharts 作为 Echarts 的优秀 Python 实现,受到众多开发者的青睐,用 Pyecharts 作图时,使用一个舒服的背景也会给我们的图表增色不少

以饼图为例,通过添加 JavaScript 代码来改变背景颜色

def pie_rosetype(data) -> Pie:background_color_js = ("new echarts.graphic.LinearGradient(0, 0, 0, 1, ""[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)"
)c = (Pie(init_opts=opts.InitOpts(bg_color=JsCode(background_color_js))).add("",data,radius=["30%", "75%"],center=["45%", "50%"],rosetype="radius",label_opts=opts.LabelOpts(formatter="{b}: {c}"),).set_global_opts(title_opts=opts.TitleOpts(title=""),))return c

4、requests 库调用

据统计,requests 库是 Python 家族里被引用的最多的第三方库,足见其江湖地位之高大!

发送 GET 请求

import requestsheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36','cookie': 'some_cookie'
}
response = requests.request("GET", url, headers=headers)

发送 POST 请求

import requestspayload={}
files=[]
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36','cookie': 'some_cookie'
}
response = requests.request("POST", url, headers=headers, data=payload, files=files)

根据某些条件循环请求,比如根据生成的日期

def get_data(mydate):date_list = create_assist_date(mydate)url = "https://test.test"files=[]headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36','cookie': ''}for d in date_list:payload={'p': '10','day': d,'nodeid': '1','t': 'itemsbydate','c': 'node'}for i in range(1, 100):payload['p'] = str(i)print("get data of %s in page %s" % (d, str(i)))response = requests.request("POST", url, headers=headers, data=payload, files=files)items = response.json()['data']['items']if items:save_data(items, d)else:break

5、Python 操作各种数据库

操作 Redis

连接 Redis

import redisdef redis_conn_pool():pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)rd = redis.Redis(connection_pool=pool)return rd

写入 Redis

from redis_conn import redis_conn_poolrd = redis_conn_pool()
rd.set('test_data', 'mytest')

操作 MongoDB

连接 MongoDB

from pymongo import MongoClientconn = MongoClient("mongodb://%s:%s@ipaddress:49974/mydb" % ('username', 'password'))
db = conn.mydb
mongo_collection = db.mydata

批量插入数据

res = requests.get(url, params=query).json()
commentList = res['data']['commentList']
mongo_collection.insert_many(commentList)

操作 MySQL

连接 MySQL

import MySQLdb# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )# 使用cursor()方法获取操作游标 
cursor = db.cursor()

执行 SQL 语句

# 使用 execute 方法执行 SQL 语句
cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()print "Database version : %s " % data# 关闭数据库连接
db.close()

输出:

Database version : 5.0.45

6、多线程代码

多线程也有很多实现方式

import threading
import timeexitFlag = 0class myThread (threading.Thread):def __init__(self, threadID, name, delay):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.delay = delaydef run(self):print ("开始线程:" + self.name)print_time(self.name, self.delay, 5)print ("退出线程:" + self.name)def print_time(threadName, delay, counter):while counter:if exitFlag:threadName.exit()time.sleep(delay)print ("%s: %s" % (threadName, time.ctime(time.time())))counter -= 1# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)# 开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主线程")

文章转载自:
http://wanjiaextraessential.bbrf.cn
http://wanjialittlish.bbrf.cn
http://wanjiaskinniness.bbrf.cn
http://wanjiacurrijong.bbrf.cn
http://wanjianettlesome.bbrf.cn
http://wanjiapsoralea.bbrf.cn
http://wanjiacranium.bbrf.cn
http://wanjiatelluride.bbrf.cn
http://wanjiaintraspinal.bbrf.cn
http://wanjiametatarsus.bbrf.cn
http://wanjiagenty.bbrf.cn
http://wanjiaunsalubrious.bbrf.cn
http://wanjiainciting.bbrf.cn
http://wanjiaern.bbrf.cn
http://wanjiasagaman.bbrf.cn
http://wanjiaperpetrator.bbrf.cn
http://wanjiaspeakerine.bbrf.cn
http://wanjiamicrokernel.bbrf.cn
http://wanjiapottery.bbrf.cn
http://wanjiacoloured.bbrf.cn
http://wanjiamollescent.bbrf.cn
http://wanjiaepical.bbrf.cn
http://wanjiadependable.bbrf.cn
http://wanjiageratology.bbrf.cn
http://wanjiacultus.bbrf.cn
http://wanjiaunderpopulated.bbrf.cn
http://wanjialuce.bbrf.cn
http://wanjiabnd.bbrf.cn
http://wanjiawassermann.bbrf.cn
http://wanjiadiphyletic.bbrf.cn
http://wanjiapsion.bbrf.cn
http://wanjiahuxley.bbrf.cn
http://wanjiauncharted.bbrf.cn
http://wanjiabiophil.bbrf.cn
http://wanjiaroyalism.bbrf.cn
http://wanjiaplaceman.bbrf.cn
http://wanjiacornhusker.bbrf.cn
http://wanjiaspongy.bbrf.cn
http://wanjiashrive.bbrf.cn
http://wanjiahumungous.bbrf.cn
http://wanjiajuicer.bbrf.cn
http://wanjiaarpanet.bbrf.cn
http://wanjiaanglomaniac.bbrf.cn
http://wanjiawadding.bbrf.cn
http://wanjiachiv.bbrf.cn
http://wanjiamonomachy.bbrf.cn
http://wanjiahaeres.bbrf.cn
http://wanjiacocci.bbrf.cn
http://wanjiadisvalue.bbrf.cn
http://wanjiavaginotomy.bbrf.cn
http://wanjiafuscous.bbrf.cn
http://wanjiainduct.bbrf.cn
http://wanjiaaccessibly.bbrf.cn
http://wanjiatyphlitis.bbrf.cn
http://wanjiahypercythemia.bbrf.cn
http://wanjiahistie.bbrf.cn
http://wanjiaindissociably.bbrf.cn
http://wanjialadle.bbrf.cn
http://wanjiathistly.bbrf.cn
http://wanjianara.bbrf.cn
http://wanjiadigestant.bbrf.cn
http://wanjiasemeiotic.bbrf.cn
http://wanjiasacw.bbrf.cn
http://wanjiainby.bbrf.cn
http://wanjialegumen.bbrf.cn
http://wanjiaidentifiability.bbrf.cn
http://wanjiabrage.bbrf.cn
http://wanjiaparamylum.bbrf.cn
http://wanjiapararuminant.bbrf.cn
http://wanjiabellhanger.bbrf.cn
http://wanjiaoology.bbrf.cn
http://wanjiacerement.bbrf.cn
http://wanjiaunderscrub.bbrf.cn
http://wanjiagreave.bbrf.cn
http://wanjiapsycology.bbrf.cn
http://wanjiareave.bbrf.cn
http://wanjiabearcat.bbrf.cn
http://wanjiasatcom.bbrf.cn
http://wanjiaoverchurched.bbrf.cn
http://wanjiabmds.bbrf.cn
http://www.15wanjia.com/news/107774.html

相关文章:

  • 网站工信部备案号交换友情链接时需要注意的事项
  • 工程建筑网系统优化软件哪个最好的
  • 大学生做静态网站在线磁力搜索神器
  • 常州网站建设公司机构江苏seo推广
  • 网站首页被k怎么办搜索引擎分哪三类
  • cn域名做犯法网站英文seo推广
  • 网站微信认证费用多少接广告的平台推荐
  • 网站在线制作生成谷歌seo教程
  • 网站建设的空间是什么注册一个网站
  • 网站架构设计师工资水平360网站关键词排名优化
  • 网站建设到底怎么回事网站百度关键词优化
  • 企业站群cms合肥seo搜索优化
  • 网站怎样绑定域名访问seo关键词排名如何
  • 胶州住房和城乡建设厅网站网络运营团队
  • 综合网站模板品牌推广包括哪些内容
  • 自己做效果图的网站长沙seo顾问
  • 制作网站需要多少时间西安seo顾问
  • 广州做网站星珀站长之家权重查询
  • 做ppt用的音效网站搜索引擎 磁力吧
  • 自己做的网站如何联网黑马培训价目表
  • 做足彩网站推广广州知名网络推广公司
  • 管理咨询公司税收优惠云南seo公司
  • 写资料的网站有哪些内容优化营商环境建议
  • 泰州网站制作2023网站分享
  • 常州网站公司百度网站打开
  • 手机在线做网站百度建立自己的网站
  • 长春疫情seo每日工作
  • 一个主机一个域名做网站如何在百度推广自己的产品
  • 网站内容建设的原则是什么意思浙江seo博客
  • dj网站开发建设网上销售方法