Python3 爬虫抓取沪市股票代码和最近收盘价

如何获取沪市、深市上市公司的股票代码、名称和最近一日的收盘价格。查看了百度股票、新浪财经等网站后,我选择东方财富网完成这项任务。东方财富网对几乎所有个股建立了股吧和个股网页。

从东方财富网股吧(http://guba.eastmoney.com/remenba.aspx)可以方便地抓取股票代码和名称,因为它们都是通过静态页面直接显示,使用requests、BeautifulSoup库和正则表达式可以很方便地获取。

查看源代码,找到显示沪市股票列表信息,它们被存放在class="ngbglistdiv"的

标签中。使用BeautifulSoup库的find_all函数查找获得
标签内的所有标签及内容。继续使用find_all查找
标签中所有的标签,并用string属性获得内容。最后分割字符串获得股票代码和股票名称。(注意:这里没有直接从
标签中获取内容或者使用正则表达式,是因为股票列表中间有一个隐藏
标签,用这种方法只能取到隐藏
标签之前的内容。)

<code>for div in soup.find_all('div',{'class':'ngbglistdiv'}):for li in div.find_all('li'): s = li.contents[0].string code = s[1:7] name = s[8:]/<code>

接下来从个股页面http://quote.eastmoney.com/sh600010.html获取最近股票成交价。观察这个链接地址,页面文件是以“sh”后面加上股票代码命名的,而前面我们已经获得了沪市的每一个股票的代码。

查看源代码,发现并不能直接在页面找到“1.14”这个价格信息,它是动态生成的。

“F12”打开开发人员工具,查看“Elements”,找到显示“1.14”这个价格所在区域。有一个“data-bind”属性等于“43”,这个就是javascript脚本加载数据的关键属性。

查看“Network”,点击“Name”区域的get请求连接,在右侧的“Headers”中注意找到“fields=f43”,这个Request URL就是实际的请求地址。

点击Headers右侧的Preview,可以看到f43:1.14,从服务器动态加载的数据被JQuery封装在一个字典当中。

复制这个Request URL在浏览器单独打开,我们需要的价格信息就在这中间。

直接使用这个Request URL有点繁琐,把没有必要的参数值全部删掉。

经过测试,问号前面的地址不变,后面的只有这3个参数有实际作用。

fltt表示小数位数,fields是我们要找的数据属性标识符,这两个也固定不变。只有secid=1.600114,小数点后边的6位数字代表的是股票代码。这样根据每一个股票代码,使用正则表达式就看可以获取到价格那个值。

<code># 根据股票代码获取最近一天收盘价
def getStockPrice(stock_code):
\turl = 'http://push2.eastmoney.com/api/qt/stock/get?fltt=2&fields=f43&secid=1.' + stock_code
\tdata = getHtmlContent(url)
\trex = re.compile('\"f43\":\\d*.\\d*')
\tm = re.search(rex,data)
\t# 返回价格
\treturn m.group(0).split(':')[1]/<code>

最后整合所有代码:

<code># _*_ coding:utf-8 _*_

import requests
from bs4 import BeautifulSoup
import re

# 获取页面函数
def getHtmlContent(url):
\ttry:
\t\tr = requests.get(url,'html.parser')
\t\tr.raise_for_status()
\t\tr.encoding = r.apparent_encoding
\t\treturn r.text
\texcept Exception as e:
\t\treturn ''

# 解析并打印
def parseHtml(html):
\tsoup = BeautifulSoup(html,'html.parser')
\tcount = 0
\ttry:
\t\tfor div in soup.find_all('div',{'class':'ngbglistdiv'}):
\t\t\tfor li in div.find_all('li'):


\t\t\t\tcount = count + 1
\t\t\t\ts = li.contents[0].string
\t\t\t\tcode = s[1:7]
\t\t\t\tname = s[8:]
\t\t\t\tprice = getStockPrice(code)

\t\t\t\tprint(count, code, name, price)
\texcept Exception as e:
\t\tprint('')

# 根据股票代码获取最近一天收盘价
def getStockPrice(stock_code):
\turl = 'http://push2.eastmoney.com/api/qt/stock/get?fltt=2&fields=f43&secid=1.' + stock_code
\tdata = getHtmlContent(url)
\trex = re.compile('\"f43\":\\d*.\\d*')
\tm = re.search(rex,data)
\t# 返回价格
\treturn m.group(0).split(':')[1]

# 主函数
if __name__ == '__main__':
\tname_url = 'http://guba.eastmoney.com/remenba.aspx'
\thtml = getHtmlContent(name_url)
\tparseHtml(html)/<code>

运行看看效果:

最终成功抓取到了沪市1559家上市公司的股票代码、股票名称和最近收盘价。

小结:现在互联网上的系统大多数页面数据都是动态加载,而且做了很多反爬措施,爬取网页内容,主要是分析清楚网页结构和数据加载的原理。

"