1. 程式人生 > 程式設計 >python3中for迴圈踩過的坑記錄

python3中for迴圈踩過的坑記錄

前言

最近在用python練習寫點爬蟲,想著把雙色球的歷史記錄爬下來存入mysql中,爬取資料沒有遇到什麼問題,在處理資料存入資料庫的時候遇到問題了,現把問題整理出來方便自己日後查詢也能幫助有緣人士:

一、從雙色球歷史網站爬取資料存成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\")" % (
  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迴圈踩坑記錄的文章就介紹到這了,更多相關python3 for迴圈踩坑內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!