爬虫—根据股票代码实时抓取股票信息
爬虫—根据股票代码实时抓取股票信息
数据来源网址:https://xueqiu.com
目标:根据输入的股票代码和证券所,实时抓取股票的交易信息
源码如下:
import requests
from lxml import etree
# 本案例数据需要账号登录之后才能获取,所以headers头部应该加cookie键值对
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Cookie': 'cookiesu=291705301257305; Hm_lvt_1db88642e346389874251b5a1eded6e3=1705301259; device_id=c0922624cb0c519d46f69c7e06d1b22c; s=a811kg480v; xq_a_tokenBuNEFadXAifQ.Fmf0Pzni2S1B9cjrrgO9JGfxXhxAcLoof_mXLwdBWiqNIzbzBxcnIFGxlJ81OANkwKcVYypwaKAHBJRDiEfnip8eh_ZMUyR48M76yOLAsnWfHve_uNP-muPRA-_mA2vf5UdLQbbIUZQox0a3xT6YzJbqIrh90rpcCyPb940gcKp6S-8Z76iOyLc943Panm3rJv_NVEdrEuXrQm9K7-17XN6KfbKaHkC1uGInssZnJunYf4P536OLT3rp96XcoBnC5zZp1N869kJINMDryIh5TTdZnqdIOPORY0ZWY-Vjm3phZKB_4drmROP-L_1H4vOn5ueJSkkN9UGb3xvTd1qOZQ; xq_is_login=1; u=1984380207; snbim_minify=true; __utma=1.618845020.1705302340.1705302340.1705302340.1; __utmc=1; __utmz=1.1705302340.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); acw_tc=2760825c17053658496137472ec8319963809c48b0f5d01ae56d064ff36917; Hm_lpvt_1db88642e346389874251b5a1eded6e3=170536619'}
# 定义一个函数,参数为股票代码和证券交易类型
def get_stock_info(stock_code, stock_type):
url = f'https://xueqiu.com/S/{stock_type + stock_code}'
res = requests.get(url, headers=headers)
if res.status_code == 200:
res.encoding = res.apparent_encoding
data = res.content.decode()
tree = etree.HTML(data)
td_lst = tree.xpath('//div[@class="quote-container"]//table[@class="quote-info"]/tr//td')
stock_name = tree.xpath('//div[@class="stock-name"]/text()')
stock_current_price = tree.xpath('//div[@class="stock-current"]')[0]
stock_change = tree.xpath('//div[@class="stock-change"]')[0]
print('股票名称及代码:', stock_name[0])
print('股票当前股价:', stock_current_price.xpath('./strong/text()')[0], '股票当前波动:', stock_change.xpath('./text()')[0])
print('股票的详细信息:')
for td in td_lst:
print(' '.join(td.xpath('.//text()')))
else:
print('请核实查询的股票代码和证券公司类型!')
if __name__ == '__main__':
stock_code = input('请输入要查询的股票代码: ')
stock_type = input('请输入证券交易所(SZ|SH):').upper()
get_stock_info(stock_code, stock_type)
运行结果如下:
雪球网股票数据.py
请输入要查询的股票代码: 002465
请输入证券交易所(SZ|SH):sz
股票名称及代码: 海格通信(SZ:002465)
股票当前股价: ¥12.15 股票当前波动: -0.04 -0.33%
股票的详细信息:
最高: 12.20
今开: 12.18
涨停: 13.41
成交量: 57873手
最低: 11.97
昨收: 12.19
跌停: 10.97
成交额: 6989.44万
量比: 1.44
换手: 0.25%
市盈率(动): 63.06
市盈率(TTM): 47.76
委比: -7.65%
振幅: 1.89%
市盈率(静): 45.13
市净率: 2.41
每股收益: 0.25
股息(TTM): 0.14
总股本: 24.82亿
总市值: 301.54亿
每股净资产: 5.04
股息率(TTM): 1.14%
流通股: 23.01亿
流通值: 279.51亿
52周最高: 14.01
52周最低: 8.27
货币单位: CNY
Process finished with exit code 0
截图所示:
原文地址:https://blog.csdn.net/weixin_41905135/article/details/135617747
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!