200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 用 selenium 统计博客总字数

用 selenium 统计博客总字数

时间:2022-04-13 11:39:16

相关推荐

用 selenium 统计博客总字数

有一天

突然想知道博客写了多少字 ⛵️​ …

1. 打开主页

利用 selemium 打开博客主页:

import timefrom selenium import webdriverbrowser = webdriver.Chrome()browser.get('/qq_41140138')browser.implicitly_wait = 5

2. 加载博客列表

由于博客列表没有显示全部博客,需要滚动到页面底部才能进一步加载内容

加载完成的标志是出现一个停留三秒钟的弹窗,所以模拟向下滚动页面

while True:# scroll 5000 per 0.2 secondsbrowser.execute_script("window.scrollBy(0,5000)")time.sleep(0.2)# finish loadingtry:browser.find_element_by_xpath('//div[@role="alert"]')print("Reach buttom!")breakexcept:continue

3. 页面跳转

获取窗口和跳转窗口的方法如下:

# 读取当前页面handle_main = browser.current_window_handle# 读取所有窗口handles = browser.window_handles# 跳转到最后一个窗口browser.switch_to.window(handles[-1])

4. 统计每篇博客字数

遍历主页中所有博客,在新的窗口定位 article 标签读取文字(忽略代码片段)

步骤:

定位博客,点击链接跳转页面,打开博客读取内容,统计字数回到博客主页

# title, content and codeblog_link_xpath = '//article[@class="blog-list-box"]//a'title_path = '//article[@class="blog-list-box"]//div[@class="blog-list-box-top"]'content_path = '//div[@class="blog-content-box"]'code_path = '//pre'handle_main = browser.current_window_handlecount = 0blog_links = browser.find_elements_by_xpath(blog_link_xpath)for blog_link in blog_links:blog_link.click()handles = browser.window_handlesbrowser.switch_to.window(handles[-1])# contentblog = browser.find_element_by_xpath(content_path)blog_title = browser.find_element_by_xpath('//h1[@class="title-article"]').textblog_content = blog.text# codecode_len = 0codes = browser.find_elements_by_xpath(code_path)for code in codes:code_len = code_len + len(code.text)# caculatecount = count + len(blog_content) - code_lenprint(blog_title + ":\t" + str(len(blog_content)-code_len) + ' words')browser.close()browser.switch_to.window(handle_main)print(count)

运行结果如下:

Reach buttom!用 Python 绘制 XMind 思维导图:937 wordsPython 多线程:1557 wordsPython socket 编程:2253 wordsAppium + Python APP 自动化测试学习:1178 words使用 xpath 选择元素:1228 wordsSelenium 元素查找和操作元素:1658 wordsPython + Appium 简单 5 步搭建环境(面向小白):1625 words一文读懂 Python 装饰器:344 wordspytest 函数测试:870 wordspytest 快速入门:622 wordsRSA 非对称加密:3241 wordsSelenium 入门学习:2278 wordsPython 面向对象:531 words...167552

一共 167552 个字 🌵

你写了多少字呢 ?

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。