请教一个问题,怎么提高 python 爬虫的爬取效率?

2016-08-25 09:45:33 +08:00
 BBrother

写了个简单的协程爬虫爬取 B 站用户信息,代码如下:

import requests
import re
import json 
import datetime
import asyncio

def get_info(uid):
    url_info = "http://space.bilibili.com/ajax/member/GetInfo?mid=" #基本信息
    uid = str(uid)
    return loop.run_in_executor(None, requests.get, url_info+uid)

    
async def user_info(num):
    for uid in range(num, num+10):
        info = await get_info(uid)
        info = json.loads(info.text)["data"]
        try:
        # print(datetime.datetime.fromtimestamp(info['regtime']))
            print("ok", uid)
            print(info)
        except UnicodeEncodeError as e:
            print("UnicodeEncodeError:", e)
        except TypeError:
            print(info)
            
loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(asyncio.wait([user_info(x) for x in range(1, 1000, 10)]))
except Exception as e:
    print("Error:", e)

爬取 1000 条需要 50 秒左右,而且带宽占用也只有 220Kbps 左右的样子,有没有什么办法提高爬取的速度? B 站用户有 3800 万左右。

谢谢指教。

ps:1. 没机器做分布式 2. 我知道多进程,但我想问问协程能不能更有效率一点。

7448 次点击
所在节点    Python
30 条回复
jason0916
2016-08-25 15:33:16 +08:00
为啥不用 aiohttp 要用 requests 呢?不会被阻塞住么?
wmjie
2016-08-25 17:48:26 +08:00
requests 会被阻塞,换成 aiohttp 试试;
https://github.com/aosabook/500lines/tree/master/crawler
soulmine
2016-08-25 18:18:48 +08:00
不挂代理池+搞分布式然后多线程 你跑到下个月也跑不完
pncltp
2016-08-25 18:27:59 +08:00
为什么要重新造轮子,用 scrapy 库呗。
mutalisk
2016-08-26 08:03:22 +08:00
requests+gevent
hard2reg
2016-08-26 14:44:04 +08:00
你好,我是 B 站的运维。我打算在后端加入反爬虫代码了!
BBrother
2016-08-26 15:48:01 +08:00
@hard2reg 不!住手! 尔康.jpg
Shliesce
2016-08-26 18:01:53 +08:00
我是 B 站的研发,我要取消这个接口了。
hard2reg
2016-08-26 20:32:10 +08:00
@BBrother 笑尿
BBrother
2016-08-29 22:35:16 +08:00
@Shliesce 你不会真是 B 站的吧?接口真没了啊。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/301628

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX