python爬取所有股票数据并保存到excel文件

 

# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 10:00:27 2020

@author: LiKely
"""


import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
import json
import xlwt

def get_list(url):
    
    # 股票代码链接
    res=requests.get(url)
    res.encoding='utf-8'
    
    # 完整HTML
    html=BeautifulSoup(res.text,'html.parser')
    
    # 股票代码列表
    stockList=[]
    
    for item in html.select('.stockTable a'):
        try:
            stockObj={}
            stockObj['name']=item.text
            stockObj['url']=item.get('href')
            stockList.append(stockObj)
        except:
            print('出现异常')
            
    return stockList


def get_detail(url):

    # 股票链接
    res=requests.get(url)
    res.encoding='utf-8'
    
    # 完整HTML
    html=BeautifulSoup(res.text,'html.parser')
    
    # 股票对象
    result={}
    result['title']=''
    result['code']=''
    result['state']=''
    result['nowtime']=''
    result['url']=''
    result['maxheight']=''
    result['minheight']=''
    result['childTitles']=[]
    result['childValues']=[]
    
    try:
        # 股票名称
        result['title']=html.select('.stock_title h1')[0].text
    except:
        print('读取股票名称,出现异常',url)
    
    try:
        # 股票代码
        result['code']=html.select('.stock_title h2')[0].text
    except:
        print('读取股票代码,出现异常',url)
    
    try:
        # 股票状态
        result['state']=html.select('.stock_title em')[0].text
    except:
        print('读取股票状态,出现异常',url)
        
    try:
       # 当前时间
        result['nowtime']=html.select('.stock_title time')[0].text
    except:
        print('读取当前时间,出现异常',url)
    
    try:
       # 股票链接
       result['url']=url
    except:
        print('读取股票链接,出现异常',url)
        
    try:
       # 最高
        result['maxheight']=html.select('.s_height dd')[0].text
    except:
        print('读取最高,出现异常',url)
        
    try:
       # 最低
        result['minheight']=html.select('.s_height dd')[1].text
    except:
        print('读取最低,出现异常',url)
    
    try:
       # 股票各项指数标题
       childTitles=[]
       for item in html.select('.s_date dt'):
           childTitles.append(item.text)
       result['childTitles']=childTitles
    except:
        print('读取股票各项指数值,出现异常',url)
    
    try:
       # 股票各项指数值
       childValues=[]
       for item in html.select('.s_date dd'):
           childValues.append(item.text)
       result['childValues']=childValues
    except:
        print('读取股票各项指数值,出现异常',url)
    
    return result


if __name__ == "__main__":          #主函数

    # 获取股票代码列表
    stockList=get_list('https://hq.gucheng.com/gpdmylb.html')
    
    # 获取股票各项指数标题列表
    firstChildTitleList=get_detail(stockList[0]['url'])['childTitles']
    
    print('获取到'+str(len(stockList))+'个股票代码')
    
    # 创建工作簿
    book = xlwt.Workbook(encoding='utf-8')
    
    # 创建工作表
    sheet = book.add_sheet('股票代码')
    
    # 创建固定表头
    head = ['股票名称','股票代码','状态','时间','网址','最高','最低']
    for h in range(len(head)):
        sheet.write(0,h,head[h])
        
    #追加各项指标表头
    for h in range(len(firstChildTitleList)):
        sheet.write(0,len(head)+int(h),firstChildTitleList[h])
    
    # 写入固定列数据
    for i,item in enumerate(stockList):
        try:
            stockObj=get_detail(item['url'])
            sheet.write(i+1,0,stockObj['title'])
            sheet.write(i+1,1,stockObj['code'])
            sheet.write(i+1,2,stockObj['state'])
            sheet.write(i+1,3,stockObj['nowtime'])
            sheet.write(i+1,4,stockObj['url'])
            sheet.write(i+1,5,stockObj['maxheight'])
            sheet.write(i+1,6,stockObj['minheight'])
            
            # 写入各项指标列数据
            for j,child in enumerate(stockObj['childValues']):
                sheet.write(i+1,7+j,child)
            
            print (str(i),'写入成功')
            # print (str(i),'写入成功',stockObj)
        except:
            print (str(i),'出现异常',stockObj['url'])

    book.save('股票代码.xls')
    
    print('写入完毕!>>股票代码.xls')

### 使用 Python 编写爬虫程序抓取天气数据导出至 Excel 为了完成这一目标,可以采用如下方法: #### 安装必要的库 在开始之前,需确保已安装用于操作Excel文件的相关库。具体来说,`xlwt` 库可用于创建新的Excel工作簿,而 `requests` 或 `BeautifulSoup` 则有助于获取网页上的信息。 ```bash pip install requests beautifulsoup4 xlwt pandas openpyxl ``` 上述命令会安装所需的所有依赖项[^1]。 #### 获取天气数据 利用 `requests` 发送HTTP请求访问提供天气预报服务的网站,通过解析HTML文档提取所需的气象参数。这里假设有一个简单的API接口或者静态页面作为数据源。 ```python import requests from bs4 import BeautifulSoup url = 'http://example.com/weather' # 替换成实际的目标URL response = requests.get(url) html_content = response.text soup = BeautifulSoup(html_content, 'lxml') weather_data = [] for item in soup.find_all('div', class_='forecast-item'): date = item.find('span', class_='date').text.strip() temperature_high = item.find('span', class_='high-temp').text.strip().replace('°C', '') temperature_low = item.find('span', class_='low-temp').text.strip().replace('°C', '') weather_data.append({ 'Date': date, 'High Temperature (℃)': float(temperature_high), 'Low Temperature (℃)': float(temperature_low) }) ``` 这段代码展示了如何从指定结构化的HTML片段中抽取日期以及最高最低气温的信息[^2]。 #### 将数据保存Excel 文件 一旦获得了想要的数据集之后,就可以借助于Pandas DataFrame对象轻松地将其转换成表格形式,最终存储为`.xlsx`格式的电子表格文件。 ```python import pandas as pd df = pd.DataFrame(weather_data) with pd.ExcelWriter('output.xlsx') as writer: df.to_excel(writer, index=False, sheet_name='Weather Data') ``` 此部分实现了将收集来的天气记录按照列的形式排列好后存入名为`output.xlsx`的工作表里[^3]。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值