写了一个程序用python+selenium做两件事:在西瓜视频官网关注500人,并且给所有的粉丝一个作品点赞和评论。本文将分享性能调优的过程。我自己也是边学边用,有错之处请朋友们见谅。
第一版 单线程串行
简单直接,打开一个浏览器窗口,用西瓜APP扫码登陆后串行做了这两件事,关注500人耗时2217s,点赞关注几十个视频耗时386s。部分源码之前分享在前文。
第二版 多线程并行
这是IO密集的程序,如果用多进程当然可以实现并行,但是理论上多线程切换开销更少,应该更高效。通过cookies共享(参考此文)的方式解决了重复扫码登陆的问题。cookies可以活七天,这期间可以反复打开多个浏览器进行访问和操作而无需登陆。
改造后的程序如下,用5个线程各关注100人,1个线程负责点赞评论。前者用时980~1200s,后者用时635s。我的机器是双核的,这个结果低于预期。进一步的分析TBD
def main():
logger.info("start the program")
driver = get_driver_and_login(cookie_json_file='cks.json',
url='https://www.ixigua.com',
wait_for_class='loginedAvatar',
login_btn_class='xg-button xg-button-primary xg-button-middle loginButton')
follow_threads = []
target = 500
n_threads = 5
for _ in range(n_threads):
th = Thread(target=follow_users, args=(target // n_threads,))
follow_threads.append(th)
for th in follow_threads:
th.start()
th10 = Thread(target=like_and_comment_followers, args=(driver,))
th10.start()
for th in follow_threads:
th.join()
th10.join()