数据爬虫:获取申万一级行业数据
    		       		warning:
    		            这篇文章距离上次修改已过451天,其中的内容可能已经有所变动。
    		        
        		                
                在Python中,可以使用requests库获取网页内容,再使用BeautifulSoup库解析网页,提取出我们需要的数据。以下是一个简单的例子,用于获取申万一级行业数据:
import requests
from bs4 import BeautifulSoup
 
def get_swjy_data():
    # 申万一级行业数据的网址
    url = 'http://www.sinomoney.com.cn/data/swjy/'
    # 发送HTTP请求
    response = requests.get(url)
    # 检查请求是否成功
    if response.status_code == 200:
        # 使用BeautifulSoup解析网页内容
        soup = BeautifulSoup(response.text, 'html.parser')
        # 找到包含数据的表格
        table = soup.find('table', {'class': 'tablelist'})
        # 提取表格中的数据
        data_rows = table.find_all('tr')[1:]  # 跳过表头
        data = []
        for row in data_rows:
            # 提取每一行的数据
            cols = row.find_all('td')
            # 确保数据格式正确
            if len(cols) == 7:
                data.append({
                    'rank': cols[0].text.strip(),
                    'industry': cols[1].text.strip(),
                    'swjy': cols[2].text.strip(),
                    'value': cols[3].text.strip(),
                    'increase': cols[4].text.strip(),
                    'market_cap': cols[5].text.strip(),
                    'industry_cap': cols[6].text.strip()
                })
        return data
    else:
        print("Failed to retrieve data, status code:", response.status_code)
        return None
 
# 使用函数获取数据
swjy_data = get_swjy_data()
# 打印获取到的数据
if swjy_data:
    for entry in swjy_data:
        print(entry)请注意,网站可能会更改其结构,这可能会影响解析代码的有效性。此外,自动抓取数据可能违反网站的服务条款,应确保您的行为符合网站规定,并尊重网站的数据使用政策。
评论已关闭