世界上最稀缺的资源是时间。
在某一瞬间我惊恐得发现,一生三万天,已过三分之一,念及年少不更事,蹉跎而过,觉得心中有愧。至今无建树,脑袋里想起一句话,“不因虚度年华而悔恨,也不因碌碌无为而羞耻”。
如今发起少年狂,对一切都感起兴趣,深知往者不可谏,来着犹可追。空有胸中之宏远,奈何路漫漫其修远,深感无力,只有择一事,写点博客吧!来一点点弥补辜负的少年时光。
准备
selenium是一个用于Web应用程序测试的工具。selenium测试直接运行在浏览器中,就像真正的用户在操作一样,我们可以用它进行爬虫。
首先需要安装selenuim和chromedriver (网上教程特别多,安装也很容易)
在帮助-关于chrome里面查看chrome对应版本要选择对应版本,我的chrome版本 89.0.4389.114 正式版本 32 位,选择的chromedriver版本是89.0.4389.23。 chromedriver下载地址: https://npm.taobao.org/mirrors/chromedriver |
最先想到的方案是从登陆页面开始,用selenium在登陆页面模拟登陆,然后获取登陆cookie,再进入博客数据页面抓数据,最终因为我比较懒,所有我决定先用chrome登陆csdn,然后再用selenium接管chrome,每次要取的时候,让程序进行刷新即可 (一直保持chrome不关闭,不退出) 。
chromedriver接管chrome
先打开windows cmd 进入chrome安装目录, (我的win10系统是在 C:\Program Files (x86)\Google\Chrome\Application) ,然后运行chrome.exe --remote-debugging-port=9000 --user-data-dir="D:\tmp\seleinumChrome
。 D:\tmp\seleinumChrome是自己随便建立的文件夹
9000是一个空闲的端口号,用netstat -ano|findstr 9000确保端口没有监听程序。然后在打开的浏览器登陆csdn。
代码
import time
import re
import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from openpyxl import Workbook
from openpyxl import load_workbook
class SeleniumTest(object):
def __init__(self):
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9000")
chrome_driver = "D:\pythonProject\KReptile\KReptilVenu\Scripts\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver, options=chrome_options)
driver.get("https://mp.csdn.net/console/dataWatch/analysis/allarticle")
time.sleep(10) #10秒足够等到ajax取完数据
# 获取统计数据
dataAnaly = driver.find_element_by_id("data-analy")
items = dataAnaly.find_elements_by_class_name('el-col')
analysDict = {
}
for webelement in items:
m = re.match(r'(\D+)(\d+)',webelement.text)
name = m.group(1)
value = m.group(2)
analysDict[name.strip()] = int(value)
analysHeader=["日期","文章总数","粉丝数","点赞数","评论数","访问量","积分","收藏数","总排名"]
# 本地的统计excel,用openpyxl库进行操作
sourcePath = "D:\\麦芒\\私域计划\\博客\\博客数据.xlsx"
wb = load_workbook(sourcePath)
ws_active = wb['Sheet']
row=[]
for headerName in analysHeader:
if headerName == "日期":
row.append(datetime.date.today().strftime("%Y/%m/%d"))
else:
row.append(analysDict[headerName])
ws_active.append(row)
wb.save(sourcePath)
if __name__ == "__main__":
instance = SeleniumTest()
运行结果:
更多方法
不想手动执行的话,把python脚本加入windows执行计划,每天执行也可以。selenuim方式的缺点就是需要将浏览器挂起,万一不小心关掉浏览器就会失败。改进方法是直接抓接口,就算浏览器关闭,只要我没有退出,也是可以通过cookie通过登陆验证。请看文章:用nodejs配合python破解X-Ca-Signature,抓取博客积分数据
参考文章:
https://blog.csdn.net/weixin_41858542/article/details/84974356