Python爬蟲之--------瀘深A股股票

如下作的項目是用Python3.5版本,爬取股票數據存儲數據庫
# coding:utf8
import re #匹配正則表達式
import requests #Requests 使用的是 urllib3,所以繼承了它的全部特性。Requests 支持 HTTP 鏈接保持和鏈接池,支持使用 cookie 保持會話,支持文件上傳,支持自動肯定響應內容的編碼,支持國際化的 URL 和 POST 數據自動編碼。
import time #時間模塊
import mysql.connector #引入數據庫模塊 ,connect是存入數據
from selenium import webdriver
#seleniumweb自動化測試工具集,包括WebDriverselenium 2.0)等。 #webdriver 操做瀏覽器

#(注:)WebDriver 經過原生瀏覽器支持或者瀏覽器擴展直接控制瀏覽器。WebDriver 針對各個瀏覽器而開發,取代了嵌入到被測 Web 應用中的 JavaScript。
與瀏覽器的緊密集成支持建立更高級的測試,避免了JavaScript 安全模型致使的限制。除了來自瀏覽器廠商的支持,WebDriver 還利用操做系統級的調用模擬用戶輸入。

# url = http://quote.stockstar.com/stock/ranklist_a_3_1_1.html #網站地址
db = mysql.connector.connect(user='root', password='12345678', host='127.0.0.1', port=3306, db='233')
cursor = db.cursor()
driver = webdriver.PhantomJS() #驅動Phjs瀏覽器
demo = re.compile(
'<tr><td.*?><a.*?>(.*?)</a></td><td.*?><a.*?>(.*?)</a></td><td.*?><span.*?>(.*?)</span></td><td.*?><span.*?>(.*?)</span></td><td.*?><span.*?>(.*?)</span></td><td.*?><span.*?>(.*?)</span></td><td.*?>(.*?)</td><td.*?>(.*?)</td><td.*?>(.*?)</td><td.*?>(.*?)</td><td.*?>(.*?)</td><td.*?>(.*?)</td><td.*?>(.*?)</td></tr>',
re.S)
while True: #此處死循環是爲了讓數據實時更新
time.sleep(4) #隔4秒更新一次數據
for i in range(1, 108): #獲取1-107頁的URL地址
url_a = "http://quote.stockstar.com/stock/ranklist_a_3_1_"
urls = url_a + str(i) + ".html"

    time.sleep(3) #讓頁面緩存3秒
driver.get(urls) #地址以js瀏覽器提交
yuan = driver.page_source #獲取源代碼
lists = demo.findall(yuan) #正則匹配源碼
# print(lists)

for a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13 in lists: #循環遍歷
# print(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13)
print('查詢--------')
sql = "select exists(select 1 from shengu where a1='" + a1 + "')" #查詢數據庫裏有沒有相對應的字段
cursor.execute(sql)
listss = cursor.fetchall() #遊標獲取遍歷後的數據
# print(listss[0][0])
if not listss[0][0]:
print('插入--------')
sql1 = "insert into shengu(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13)VALUES ('" + a1 + "','" + a2 + "','" + a3 + "','" + a4 + "','" + a5 + "','" + a6 + "','" + a7 + "','" + a8 + "','" + a9 + "','" + a10 + "','" + a11 + "','" + a12 + "','" + a13 + "')"
cursor.execute(sql1)
db.commit()
else:
print('更新---------')
sql2 = "update shengu set a1='" + a1 + "',a2='" + a2 + "',a3='" + a3 + "',a4='" + a4 + "',a5='" + a5 + "',a6='" + a6 + "',a7='" + a7 + "',a8='" + a8 + "',a9='" + a9 + "',a10='" + a10 + "',a11='" + a11 + "',a12='" + a12 + "',a13='" + a13 + "' where a1='" + a1 + "'"
cursor.execute(sql2) db.commit()#經測試代碼有效#代碼有哪裏不足的地方望大神及各位指教,謝謝
相關文章
相關標籤/搜索