用asyncio和aiohttp异步协程爬取披露易网站港资持股数据

这是本人毕设项目的一部分,也是比较核心的部分。
请自觉遵守相关法律法规,若侵权请联系本人立刻删除。

任务描述

爬取披露易网站上的港资持股A股详细股东数据。点击搜索栏下方的持股名单我们可以看到港资持股的股份名单。
任务分为三部分:

  • 首先需要爬取港资持股名单
  • 根据持股名单依次搜索爬取机构详细持股数据
  • 将爬取到的数据存入到mysql数据库中
    我们以股份【四川成渝高速公路,00107】为例,点击搜索,得到如下页面:
    在这里插入图片描述
    可以看到,对于一只股票而言,港资机构很多,我们只需要截取持股数量最大的前20名股东数据即可,如果不足20名就全部截取。另外我们所需要的字段有参与者编号参与者名称持股数量占中央结算系统的比例。也就是股东编号,股东名称,股东持股数量和股东持股比例。

解决方案

笔者试过很多的解决方案,但是效果都不佳,常见的问题有:发起请求的时候容易失败,请求速度过快容易被封IP,使用多线程时容易遇到莫名其妙的问题(比如直接卡死也不知道什么原因)。经过无数次的打磨,最终得到一个比较合理的方案。

问题分析

首先对于股份名单的爬取自不必说,页面是一个表格,相对而言是一个简单的任务,而且只需要爬取一次。所以只需要发起一次请求获取到页面,然后将页面解析得到股份代码即可。

核心问题在于得到股份名单之后,需要将需要爬取的日期和股份代码输入,然后获取详细持股页面,这个过程可以发起一个post请求解决。难点在于股份名单中A股大概有2400支,那么每天需要对每一支股票的前20名股东进行爬取(有的不足20名),那么大概就总共有3万到4万条数据。

之前笔者低估了pymysql的力量,认为一次性插入上万条数据是非常耗时间的,需要采取特别的方案,例如多线程,协程等。但是事实证明,一次性插入上万条数据只不过需要10秒左右,因此对于数据插入的问题不予考虑优化。

现在剩余的唯一问题是,如何向同一个网站发起2400次请求?

当然,若你时间充裕,你用一天的时间来慢慢请求倒是无所谓,但是股票数据涉及到及时性的问题,需要尽快更新以便为用户提供服务。因此,爬虫速度以及不被封IP是一个迫切需要考虑的问题。

解决方案1
爬取股份名单

这里先贴出爬取股份名单的代码

import requests
def get_stock_list(day):
        """获取股票代码

        Args:
            day (str)): 形如 20200101
        """
        url = "https://sc.hkexnews.hk/TuniS/www.hkexnews.hk/sdw/search/stocklist_c.aspx"
        params = {
            "sortby":"stockcode",
            "shareholdingdate":day,
        }
        #发送一个get请求
        response = requests.get(url = url, params=params, headers = headers)
        if response.status_code == 200:
            print("get stock list sucess!")
        soup = BeautifulSoup(response.text,'lxml')
        code_list = []
        trs = soup.select("table > tbody > tr")
        for tr in trs:
            tds = tr.find_all('td')
            code = tds[0].string.strip()
            code_type = code[0]
            #只需要A股股份名单
            if code_type == '7' or code_type == '3' or code_type == '9':
                code_list.append(code)
        return code_list

这一部分的代码比较简单,但是偶尔也会出问题,例如当请求失败了该如何处理并没有考虑。

爬取详细持股数据

这里将问题分解为三个任务:

  1. 根据股份代码和日期发起一次post请求,获取html页面
  2. 对html页面进行解析,得到规定格式的数据
  3. 将数据存入到数据库中

笔者之前的解决方案为将三个任务分开,并且考虑对第3步也做优化(用aiomysql来异步写入数据库),实际上大可不必。对于任务2,笔者尝试过3种方法:

  • 使用多进程(2核4G CPU):没有明显的速度提升
  • 使用线程池,系统自动决定启用多少个线程:需要耗费大概100到120秒的时间
  • 将解析和获取页面绑定为一个协程任务进行(后面细说)

这里先贴出详细持股页面解析的代码

#datas是一个全局变量
#传入code参数是为了构造一项数据 [code,holder_id,volume,percent]
#没有爬取股东名称是因为另外有股东简称数据,此处不需要
def parse_html(code,html):
    soup = BeautifulSoup(html,'lxml')
    trs = soup.select("table > tbody > tr")
    count = 20 #只获取前20名股东的持股数据
    for tr in trs:
        count = count - 1
        if count<0:
            break
        tds = tr.find_all('td')
        holder_id = tds[0].select(".mobile-list-body")[0].string
        volume = tds[3].select(".mobile-list-body")[0].string 
        volume = ''.join((str(x) for x in volume.split(','))) #去掉逗号
        percent = tds[4].select(".mobile-list-body")[0].string
        percent = percent[:-1] #去掉百分号
        item = (code, holder_id, volume, percent) #code,...
        if holder_id is not None:
            #香港中央结算系统没有holder_id,为None
            datas.append(item) 

如果使用多线程进行解析:

前提:有一个全局变量htmls保存了所有股份的页面。线程池参考

from concurrent.futures import ThreadPoolExecutor, as_completed
with ThreadPoolExecutor() as t:
	for html in htmls:
		t.submit(parse_html,(html,))
aiohttp,asyncio 异步协程发起请求

经了解,python3中加入了asyncio来实现异步线程,能够对爬虫速度有质的提升。asyncio不用介绍,读者自行了解,aiohttp是发起异步请求的库。笔者突发奇想,何不将发起请求和解析页面直接作为一个协程任务进行呢?于是有了如下代码:

async def get_and_parse_html(code,day):
	#构造post参数
    data = {
        "txtStockCode": code,
        "txtShareholdingDate": day,
        "__EVENTTARGET": "btnSearch",
        "sortBy":"shareholding",
        "sortDirection":"desc",
    }
    try:
        with(await sem):
        #sem是异步请求的并发量,sem = asyncio.Semaphore(60)
        #经过测试,控制在60比较合适,否则容易被封IP
            async with aiohttp.ClientSession() as session:
            	#发起异步post请求
                async with session.post(url = url, headers=headers, data=data,timeout=20) as response:
                    if response.status==200:
                        html = await response.text()
                        # htmls.append((code,html))
                        #获取到页面就立刻开始解析,捆绑作为一个任务来完成
                        parse_html(code,html)
                    else:
                        failed_code.append(code) #失败代码,等待重新发起请求
    except Exception as e:
        failed_code.append(code)
        print(code,e)

最后是将所有的股份代码传入该函数形成任务列表,然后启动任务列表,系统将会自动执行这些任务。

def run(day):
#day:形如2022/03/22
    global failed_code
    codes = get_stock_list(day.replace('/',''))
    loop = asyncio.get_event_loop() #获取事件循环
    tasks = [get_and_parse_html(code,day) for code in codes] #构建任务列表
    loop.run_until_complete(asyncio.wait(tasks)) #激活协程
    count = 3
    while(failed_code and count>0):
        count = count - 1
        print("失败数量为%d"%(len(failed_code)))
        new_tasks = [get_and_parse_html(code,day) for code in failed_code]
        failed_code = [] #清空失败列表
        print("time sleep 10 for new task")
        time.sleep(10)
        loop.run_until_complete(asyncio.wait(new_tasks))
    print("依然剩余%d的失败数量"%(len(failed_code)))
    loop.close() #关闭事件循环

如上述代码所示,我们启动了一个事件循环,并构造了一个任务列表。codes是我们先前爬取的股份名单,failed_code是一个全局变量,存储着请求失败的代码,他们将会在第一次事件循环结束之后重新发起请求,并且有3次机会。启动协程总结如下:

  • 获取事件循环 loop = asyncio.get_event_loop()
  • 构造任务列表 tasks = [get_and_parse_html(code,day) for code in codes]
  • 激活协程任务 loop.run_until_complete(asyncio.wait(tasks))
写入数据库

最后就是写入数据库,经过前面的步骤,我们有了一个全局变量datas存储了所有的数据,其内容大致如下:

[item1,item2,item3,...]
#其中一个item为一条数据:
(code, holder_id, volume, percent)

写入数据库的代码如下:

def write_to_mysql(day):
    connection = pymysql.connect(
        host = 'localhost',
        port = 3306,
        user = 'root',
        password = 'your_password',
        database = 'your_data_base',
        charset= 'utf8' 
    )
    cursor = connection.cursor()
    sql = f"INSERT INTO HolderTable(trade_date,stock_code,holder_id,volume,percent) VALUES('{day}',%s,%s,%s,%s)"
    try:
        cursor.executemany(sql,datas)
        connection.commit()
    except:
        connection.rollback()
    connection.close()

至此,我们完成了整个任务,总共用时根据网络情况不一,快一点在150秒左右,慢一点400秒左右,但是相对于之前的半个小时,15分钟,速度已经有了很大的提升。

番外篇

在此记录其他的一些试图但是并未成功或实现不稳定的解决方案。

使用代理爬虫

使用代理爬虫,我们就需要一些代理,这些代理从何而来呢?当然也是爬虫!
如下记录了一些常见代理网站的解析代码。

    def crawl_66ip(self):
        """
        66ip 代理:http://www.66ip.cn
        """
        self.result = []
        url = (
            "http://www.66ip.cn/nmtq.php?getnum=100&isp=0"
            "&anonymoustype=0&area=0&proxytype={}&api=66ip"
        )
        pattern = "\d+\.\d+.\d+\.\d+:\d+"

        items = [(0, "http://{}"), (1, "https://{}")]
        for item in items:
            proxy_type, host = item
            html = requests(url.format(proxy_type))
            if html:
                for proxy in re.findall(pattern, html):
                    self.result.append(host.format(proxy))

    def crawl_kuaidaili(self):
        """
        快代理:https://www.kuaidaili.com
        """
        self.result = []
        url = "https://www.kuaidaili.com/free/{}"

        items = ["inha/1/"]
        for proxy_type in items:
            html = requests(url.format(proxy_type))
            if html:
                doc = pyquery.PyQuery(html)
                for proxy in doc(".table-bordered tr").items():
                    ip = proxy("[data-title=IP]").text()
                    port = proxy("[data-title=PORT]").text()
                    if ip and port:
                        self.result.append("http://{}:{}".format(ip, port))
    def crawl_ip3366(self):
        """
        云代理:http://www.ip3366.net
        """
        self.result = []
        url = "http://www.ip3366.net/?stype=1&page={}"

        items = [p for p in range(1, 8)]
        for page in items:
            html = requests(url.format(page))
            if html:
                doc = pyquery.PyQuery(html)
                for proxy in doc(".table-bordered tr").items():
                    ip = proxy("td:nth-child(1)").text()
                    port = proxy("td:nth-child(2)").text()
                    schema = proxy("td:nth-child(4)").text()
                    if ip and port and schema:
                        self.result.append("{}://{}:{}".format(schema.lower(), ip, port))

    def crawl_data5u(self):
        """
        无忧代理:http://www.data5u.com/
        """
        self.result = []
        url = "http://www.data5u.com/"

        html = requests(url)
        if html:
            doc = pyquery.PyQuery(html)
            for index, item in enumerate(doc("li ul").items()):
                if index > 0:
                    ip = item("span:nth-child(1)").text()
                    port = item("span:nth-child(2)").text()
                    schema = item("span:nth-child(4)").text()
                    if ip and port and schema:
                        self.result.append("{}://{}:{}".format(schema, ip, port))

    def crawl_iphai(self):
        """
        ip 海代理:http://www.iphai.com
        """
        self.result = []
        url = "http://www.iphai.com/free/{}"

        items = ["ng", "np", "wg", "wp"]
        for proxy_type in items:
            html = requests(url.format(proxy_type))
            if html:
                doc = pyquery.PyQuery(html)
                for item in doc(".table-bordered tr").items():
                    ip = item("td:nth-child(1)").text()
                    port = item("td:nth-child(2)").text()
                    schema = item("td:nth-child(4)").text().split(",")[0]
                    if ip and port and schema:
                        self.result.append("{}://{}:{}".format(schema.lower(), ip, port))

    def crawl_swei360(self):
        """
        360 代理:http://www.swei360.com
        """
        self.result = []
        url = "http://www.swei360.com/free/?stype={}"

        items = [p for p in range(1, 5)]
        for proxy_type in items:
            html = requests(url.format(proxy_type))
            if html:
                doc = pyquery.PyQuery(html)
                for item in doc(".table-bordered tr").items():
                    ip = item("td:nth-child(1)").text()
                    port = item("td:nth-child(2)").text()
                    schema = item("td:nth-child(4)").text()
                    if ip and port and schema:
                        self.result.append("{}://{}:{}".format(schema.lower(), ip, port)) 

然后每次我们随机运行一个函数来获取代理IP。

class ProxyCrawler:
    def __init__(self):
        self.result = [] #代理结果
        self.valid_result = [] #验证可用之后的结果
        self.func_name = ["crawl_66ip", "crawl_kuaidaili", "crawl_ip3366", "crawl_data5u",\
             "crawl_iphai", "crawl_swei360"]
 #...各个代理的爬取代码(在上面)
	#随机运行一个
    def get_proxies(self):
        self.result = []
        count = 20
        while count>0 and self.result==[]:
            count = count - 1
            id = random.randint(0,len(self.func_name)-1) 
            func = getattr(self,self.func_name[id],self.err_func)
            func()

获取的代理不一定可用,还需要进行验证,验证方法就是向我们的目标网站发起请求看是否可用。

headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Mobile Safari/537.36',
        'Connection': 'close'
    }

url = "https://www.hkexnews.hk/sdw/search/searchsdw_c.aspx"

data = {
        "txtStockCode": '30002',
        "txtShareholdingDate": '2022/03/22',
        "__EVENTTARGET": "btnSearch",
        "sortBy":"shareholding",
        "sortDirection":"desc",
    }

    def valid_normal(self,proxy):
        response = req.post(url=url,data=data,headers=headers,proxies={'http':proxy},timeout=5)
        if response.status_code == 200:
            print(f'{proxy} is useful.')
            self.valid_result.append(proxy)

有了这些可用代理之后就可以应用到正式的爬虫任务中了。

使用多线程爬虫

该方案在之前一直可行,但是2400支股票使用多线程容易卡死,因此分为了两个任务,每次用多线程爬取1200支股票数据。大概需要400秒。
核心代码如下:

#请求并解析数据
def fetch(params):
    code = params[0]
    day = params[1]
    day_ = day[:4] + '-' + day[4:6] + '-' + day[6:]
    data = {
        "txtStockCode": code,
        "txtShareholdingDate": day,
        "__EVENTTARGET": "btnSearch",
        "sortBy":"shareholding",
        "sortDirection":"desc",
    }
    retry = 5
    try:
        headers['User-Agent'] = random.choice(user_agent_list)
        response = requests.post(url = url, headers=headers, data=data)
        while(response.status_code != 200 and retry>0):
            retry = retry - 1
            time.sleep(3)
            response = requests.post(url = url, headers=headers, data=data)
        soup = BeautifulSoup(response.text,'lxml')
        trs = soup.select("table > tbody > tr")
        res = []
        count = 20 #只获取前20名股东的持股数据
        for tr in trs:
            count = count - 1
            if count<0:
                break
            tds = tr.find_all('td')
            holder_id = tds[0].select(".mobile-list-body")[0].string
            volume = tds[3].select(".mobile-list-body")[0].string 
            volume = ''.join((str(x) for x in volume.split(','))) #去掉逗号
            percent = tds[4].select(".mobile-list-body")[0].string[:-1] #去掉百分号
            item = [day_, code, holder_id, volume, percent]
            if holder_id is not None:
                #香港中央结算系统没有holder_id,为None
                res.append(item)
        return res
    except Exception as e:
        print(code,e)


def write_to_db(res_table):
    df = DataFrame(res_table, columns=[
                   'trade_date', 'stock_code', 'holder_id', 'volume', 'percent'])
    df.to_sql('HolderTable', engine_ts, index=False,
              if_exists='append', chunksize=5000)

def run(codes):
    executor = ThreadPoolExecutor()
    tasks = [executor.submit(fetch, (code)) for code in codes]
    for future in as_completed(tasks):
        data = future.result()
        write_to_db(data)
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值