温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在python3项目中使用for循环时会遇到哪些问题

发布时间:2020-12-15 15:33:05 来源:亿速云 阅读:322 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关在python3项目中使用for循环时会遇到哪些问题,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

一、从双色球历史网站爬取数据存成html文件;

import urllib.request   url = 'https://datachart.500.com/ssq/history/newinc/history.php?start=1&end=20109' request = urllib.request.Request(url) request.add_header('user-agent',      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36') response = urllib.request.urlopen(request) buf = response.read() data = buf.decode('utf-8') # 爬取数据保存到文件 fileOb = open('history.html', 'w', encoding='utf-8') # 打开一个文件,没有就新建一个 fileOb.write(data) fileOb.close()

在python3项目中使用for循环时会遇到哪些问题

二,读取html文件获取数据,其中还有mysql的连接池

from lxml import etree from collections import namedtuple import mysql2   fileOb = open('history.html', 'r', encoding='utf-8') # 打开一个文件 doc = fileOb.read() html = etree.HTML(doc) # 把字符串转化为可处理的格式 two_colour = namedtuple('two_colour', 'code,red_1,red_2,red_3,red_4,red_5,red_6,blue,create_date')     # two_colour = namedtuple('two_colour', 'a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16')     def test1():  # red = html.xpath("//tbody/tr/td[@class='t_cfont2']/text()[1]")  # blue = html.xpath("//tbody/tr/td[@class='t_cfont4']/text()[1]")  all_ball = html.xpath("//tbody/tr[@class='t_tr1']/td/text()")  # print(all_ball)  for i in range(len(all_ball)):   dict = two_colour(all_ball[0], all_ball[1], all_ball[2], all_ball[3], all_ball[4], all_ball[5], all_ball[6],        all_ball[7], all_ball[15])   print(dict)   for j in range(16):    del all_ball[0]   mysql2.saveDouBan(dict)  print(all_ball)     if __name__ == '__main__':  test1()

mysql的连接池

import pymysql # 新的写法,要注意 from dbutils.pooled_db import PooledDB   POOL = PooledDB(  creator=pymysql, # 使用链接数据库的模块  maxconnections=6, # 连接池允许的最大连接数,0和None表示不限制连接数  mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建  maxcached=5, # 链接池中最多闲置的链接,0和None不限制  maxshared=3,  # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。  blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错  maxusage=None, # 一个链接最多被重复使用的次数,None表示无限制  setsession=[], # 开始会话前执行的命令列表。  ping=0,  # ping MySQL服务端,检查是否服务可用。  host='127.0.0.0',  port=3306,  user='root',  password='123456',  database='python_test',  charset='utf8' )     def func():  # 检测当前正在运行连接数的是否小于最大链接数,如果不小于则:等待或报raise TooManyConnections异常  # 否则 则优先去初始化时创建的链接中获取链接 SteadyDBConnection。  # 然后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。  # 如果最开始创建的链接没有链接,则去创建一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。  # 一旦关闭链接后,连接就返回到连接池让后续线程继续使用。  conn = POOL.connection()    # print(th, '链接被拿走了', conn1._con)  # print(th, '池子里目前有', pool._idle_cache, '\r\n')    cursor = conn.cursor()  cursor.execute('select * from two_clour_two')  result = cursor.fetchall()  for i in result:   print(i)  conn.close()     # 数据库插入操作 def saveDouBan(dict):  conn = POOL.connection()  cursor = conn.cursor()  sql = "insert into two_clour_two (`code`, `red_1`, `red_2`, `red_3`, `red_4`, `red_5`, `red_6`, `blue`,`create_date`) values(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" % (   str(dict[0]), str(dict[1]), str(dict[2]), str(dict[3]), str(dict[4]), str(dict[5]), str(dict[6]),   str(dict[7]), str(dict[8]))  cursor.execute(sql)  print('Successful')  conn.commit() # 写入数据库一定要commit,否则数据没有数据  cursor.close()     if __name__ == '__main__':  func()

三,数据处理的误区,这个是刚开始的写法,i是下标,取完数据把对应的下标的元素删除了,可以这时候的问题就是,下标的数字比数组长了,所有最后下标取完了,可是数组却没有为空。

解决办法就是上面贴的

for i in range(len(all_ball)):

在python3项目中使用for循环时会遇到哪些问题

上述就是小编为大家分享的在python3项目中使用for循环时会遇到哪些问题了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI