如何用Python批量抓取东方财富网页内的表格?

如何用Python从东方财富网页中批量抓取表格?
网址如下:
http://emweb.securities.eastmoney.com/PC_HSF10/ShareholderResearch/Index?type=web&code=sz000001

现有一个股票代码列表文件1.txt,逐个替换上述网址中“=”号后的内容,爬取网页内的第2个表格内容,分别存入到以股票代码命名的Excel文档中。

谢邀~
既然你提了,那我必须满足呀。 你txt里面的格式要这样,

img

放到和python文件同一目录下(如果你要改,就自己改一下路径也行):

然后运行以下代码:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
# 读取股票代码列表
with open('1.txt', 'r') as f:
    stock_codes = f.read().splitlines()
headers={
'Accept':'*/*',
'Accept-Encoding':'gzip, deflate',
'Connection':'keep-alive',
'Referer':'http://emweb.securities.eastmoney.com/PC_HSF10/ShareholderResearch/Index?type=web',
'Host':'emweb.securities.eastmoney.com',
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'}
for gpdm in stock_codes:
    url='http://emweb.securities.eastmoney.com/PC_HSF10/ShareholderResearch/PageAjax?code='+gpdm
    print("正在获取股票{}的数据".format(gpdm))
    res=requests.get(url,headers=headers)
    if res.status_code==200:
        soup=BeautifulSoup(res.text,"html.parser")
        target=res.json()['sdltgd']
        df = pd.DataFrame(target)
        df.to_excel(gpdm+'.xlsx', index=False)
        time.sleep(1)
    else:
        print("股票{}的数据获取失败,获取下一个股票!".format(gpdm))
        continue

有啥需要,记得找我~

requests 请求
pandas.read_html 提取表格
pandas.to_excel 写入Excel

给你个示例,具体基于它继续修改

import requests
import pandas as pd

# 读取股票代码列表
with open('1.txt', 'r') as f:
    stock_codes = f.read().splitlines()

# 对每个股票代码进行处理
for stock_code in stock_codes:
    url = f'http://emweb.securities.eastmoney.com/PC_HSF10/ShareholderResearch/Index?type=web&code={stock_code}'
    
    # 发送GET请求
    response = requests.get(url)
    
    # 使用pandas读取网页中的表格
    tables = pd.read_html(response.text)
    
    # 我们想要的表格是第2个表格,索引为1
    df = tables[1]
    
    # 将数据保存为Excel文件,文件名为股票代码
    df.to_excel(f'{stock_code}.xlsx', index=False)



如果有帮助,请点击一下采纳该答案~谢谢

谢谢楼上的解答。但这段代码运行有问题,如下:
Traceback (most recent call last):
......
ValueError: No tables found

  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/7631138
  • 这篇博客也不错, 你可以看下python如何操作.txt文件使其居中显示(可处理多列)
  • 除此之外, 这篇博客: python实现图书管理系统——通过excel文件或者TXT文件存放数据中的 用python实现图书管理系统——通过excel文件或者TXT文件存放数据 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 话不多说,先上图,看看运行起来的效果:
    运行效果图由上图可知,我实现的主要功能:

    1. 用户注册
    2. 用户登录
    3. 添加图书
    4. 查询图书
    5. 删除图书
    6. 修改图书信息
    7. 观看所有图书信息
      接下来详细介绍每个功能如何实现:
      (这里,我分别用了两种方法实现对数据的运用)
      在整个程序之前我先声明了两个全局变量,用于设立字典列表,分别存放用户信息和书籍信息:
    users = []
    books = []
    

    举个例子,表明字典列表的详情:

    在这里插入图片描述

  • 您还可以看一下 赵帅老师的Python爬虫基础&商业案例实战课程中的 批量生成舆情报告准备知识点:自动生成txt文件小节, 巩固相关知识点
  • 以下回答由chatgpt基于相关博客总结生成:

    我能够提供一个可能的解决方案:

    1. 导入必要的库, 包括requests, BeautifulSoup, pandas和xlwt
    import requests
    from bs4 import BeautifulSoup
    import pandas as pd
    import xlwt
    
    1. 定义一个函数用于抓取单个股票代码对应网址中的表格数据并将其存储为Excel文件。其中,函数的输入参数为股票代码和Excel文件路径。
    def crawl_and_save(code, excel_path):
        # 构建股票代码对应的网址
        url = 'http://quote.eastmoney.com/stock/%s.html' % code
        # 获取网页内容
        response = requests.get(url)
        # 提取网页中第2个表格数据并转换成DataFrame格式
        soup = BeautifulSoup(response.content, 'html.parser')
        data = []
        table = soup.findAll('table')[1]
        rows = table.findAll('tr')
        for tr in rows:
            cols = tr.findAll('td')
            row = []
            for td in cols:
                row.append(td.text.strip())
            data.append(row)
        table_data = pd.DataFrame(data)
        # 将DataFrame写入Excel文件
        sheet_name = code
        writer = pd.ExcelWriter(excel_path)
        table_data.to_excel(writer, sheet_name=sheet_name)
        writer.save()
    
    1. 定义一个主函数用于批量抓取股票数据和存储为Excel文件。其中,函数的输入参数为股票代码列表和Excel文件夹路径。
    def batch_crawl_and_save(codes, excel_folder):
        for code in codes:
            excel_path = '%s%s.xlsx' % (excel_folder, code)
            crawl_and_save(code, excel_path)
    
    1. 调用主函数批量抓取股票数据并存储为Excel文件。其中,股票代码列表和Excel文件夹路径需要根据具体情况进行修改。
    codes = ['600000', '600001', '600002'] # 修改为需要抓取的股票代码列表
    excel_folder = './data/' # 修改为Excel文件夹路径
    batch_crawl_and_save(codes, excel_folder)
    

    以上就是一个简单的解决方案,其中还有许多细节需要根据具体情况进行修改。