平安银行(000001)资金流向 _ 数据中心 _ 东方财富网 (eastmoney.com)
#coding=utf-8
from selenium import webdriver #导入模块
import time
import csv #存储数据
from lxml import etree #lxml库是一个HTML、XML的解析器
import pandas as pd
import sqlalchemy
from sqlalchemy import create_engine
第一步:启动浏览器
option = webdriver.ChromeOptions() #创建一个配置对象(ChromeOptions是控制Chrome启动属性的类)
option.add_argument('headless') #添加启动参数add_argument为'headless',开启无界面模式(设置浏览器静默,让浏览器在后台运行,不需要加载样式和渲染)
driver = webdriver.Chrome(options=option) #用webdriver启动浏览器(实例化带有配置的driver对象)
driver.get('http://data.eastmoney.com/zjlx/000001.html') #跳转到指定的url地址(请求地址)
time.sleep(2)
第二步:获取页面源码并解析
xpath使用方法:(16条消息) xpath详解_baidu_32542573的博客-CSDN博客
source = driver.page_source #获取页面源码
mytree = etree.HTML(source) #解析网页
#用xpath获取所需的内容,返回一个列表
tables = mytree.xpath("//div[@id='table_ls']/table")[0] #定位表格table
trs = tables.xpath('.//tr') #取出所有tr标签(每一行单元格)
onetable=[]
for tr in trs:
ui = []
for td in tr:
texts = td.xpath(".//text()") #取出所有td标签下的文本(每个单元格)
mm = []
for text in texts:
mm.append(text.strip(" ")) #去除文本前后空格
ui.append(','.join(mm)) #字符连接,以逗号分隔
onetable.append(ui) #每行数据ui作为一个元素加入列表onetable,跑完整张表格
第三步:将数据写入csv
with open('stock.csv', 'a', newline='') as file:
csv_file = csv.writer(file) #写入csv文件
for i in onetable:
csv_file.writerow(i) #按行(ui)将数据写入
第四步:处理csv文件
df = pd.read_csv(open(r'C:\Users\DELL\stock.csv'),sep='\t',header=None)
df.drop(df.index[0:2],inplace=True)
df.columns=['raw']
df['日期']=df['raw'].str.split(',').str[0]
df['收盘价']=df['raw'].str.split(',').str[1]
df['涨跌幅']=df['raw'].str.split(',').str[2]
df['主力净流入-净额']=df['raw'].str.split(',').str[3]
df['主力净流入-净占比']=df['raw'].str.split(',').str[4]
df['超大单净流入-净额']=df['raw'].str.split(',').str[5]
df['超大单净流入-净占比']=df['raw'].str.split(',').str[6]
df['大单净流入-净额']=df['raw'].str.split(',').str[7]
df['大单净流入-净占比']=df['raw'].str.split(',').str[8]
df['中单净流入-净额']=df['raw'].str.split(',').str[9]
df['中单净流入-净占比']=df['raw'].str.split(',').str[10]
df['小单净流入-净额']=df['raw'].str.split(',').str[11]
df['小单净流入-净占比']=df['raw'].str.split(',').str[12]
del df['raw']
第五步:DataFrame写入MySQL
conn = create_engine('mysql+pymysql://root:123@localhost:3306/crawl?charset=utf8')
df.to_sql(name='df_2', con=conn,if_exists='replace',index=False,
dtype={'日期': sqlalchemy.types.String(length=20),
'收盘价': sqlalchemy.types.String(length=20),
'涨跌幅': sqlalchemy.types.String(length=20),
'主力净流入-净额': sqlalchemy.types.String(length=20),
'主力净流入-净占比': sqlalchemy.types.String(length=20),
'超大单净流入-净额': sqlalchemy.types.String(length=20),
'超大单净流入-净占比': sqlalchemy.types.String(length=20),
'大单净流入-净额': sqlalchemy.types.String(length=20),
'大单净流入-净占比': sqlalchemy.types.String(length=20),
'中单净流入-净额': sqlalchemy.types.String(length=20),
'中单净流入-净占比': sqlalchemy.types.String(length=20),
'小单净流入-净额': sqlalchemy.types.String(length=20),
'小单净流入-净占比': sqlalchemy.types.String(length=20)
})
print('ok')
第六步:关闭浏览器
time.sleep(2)
driver.close() #关闭