一 、股票代码获取
最近入坑股市,摸爬滚打,只觉得自己长高了一茬,依旧是韭菜被无情收割呜呜呜呜,因此想了想弄个,所有股票的数据来看下资金动向,类似于龙虎板但是跨度大些。
从网上看了些资源发现并没有自己想要的,最好的一个也是多个文件拆分开的而且没有相应股票的代码,所以我弄了个EXCEL整合版本。
首先我们从http://quote.eastmoney.com/stock_list.html获取相应股票:
方法一:
CTRL+C 以及CTRL+V 也就是我们常说的CV工程师,复制下到EXCEL然后进行下数据处理 处理干净放到TXT里面为后面的股票信息做准备。
方法二:
多次从这个网页元素获取股票代码,发现股票代码抓取不全,可以推测该网页可能是异步加载,就是说不进行翻滚网页情况下数据获取是不全面的,因此需要用到 Python 使用selenium+webdriver爬取动态网页内容这篇文章已经写得很详细了
如果想了解相关的静态网页获取数据的方法以及解析过程可以看我之前写的Python爬取百度搜索的标题和真实URL的代码和详细解析
获取股票的代码如下:
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
import csv
import os
file=r'C:\Users\xxp\.spyder-py3\testcode\test\stock_data.csv'#生成文件路径
def data_write_csv(file, datas):#file为写入CSV文件的路径,datas为要写入数据列表
with open(file,'a+',encoding='utf-8-sig',newline='') as f:
writer = csv.writer(f)
for data in datas:
writer.writerow(data)
print("保存文件成功,处理结束")
def get_info():
total_title=[]
total_content=[]
total_info=[]
url = 'http://quote.eastmoney.com/stock_list.html'
#r = s.get(url=url)
#r.encoding = 'GBK'
driver = webdriver.Chrome()
r = driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
#print(soup)
for n in range(0,7500,2500):
driver.execute_script('window.scrollBy(0,'+ str(n) +')')#进行页面翻滚
for so in soup.select('#quotesearch ul a'):
#print(so)
g_title = so.get('href')
#print(g_title)
#print(g_title)
g_content=so.get_text().strip()#根据分析标题无对应标签 只能获取标签内文字 去掉换行和空格
#print(g_content)
#print(g_title,g_content)
total_title +=[g_title]
total_content +=[g_content]
# print (total_title)
# print (total_content)
total_info=zip(total_title,total_content)#合并
print (total_info)
if os.path.exists(file): #文件检测
data_write_csv(file,total_info)# 进行excel写入
else: #文件不存在就创建
df=pd.DataFrame(data=total_info,columns=['title','内容'])
df.to_csv(file,index=False,encoding='utf_8_sig')
print ('文件创建成功')
if __name__ == '__main__':
get_info()
生成数据后,进行数据清洗(excel里面自己手动下就好了 去重 、分列 获取代码 ) 进行去重、2次分列即可
后续进行数据的替换原因在下一篇文章所用到的股票代码数据相关,sz替换成0. sh替换成1. 存成txt文档,后续第二篇文章会用到相关股票代码数据
后续文章:Python获取所有股票代码以及股票历史成交数据分析(二)