Selenium 根据输入的关键字来爬取微信公众号文章并保存为pdf与长图片(2022-06-09更新版)

  • 1、搭建环境:Selenium+ChromeDriver+pyautogui
    • 1.1 安装包
    • 1.2、查看你的浏览器的版本
    • 1.3、下载对应版本的ChromeDriver驱动
    • 1.4、设置环境变量(选做)
    • 1.5、暂时关闭浏览器设置中的“下载前询问每个文件的保存位置”
  • 2、配置参数,使用驱动打开谷歌浏览器
  • 3、扫码登录搜狗微信
  • 4、输入关键字,点击搜索按钮
  • 5、爬取文章,并保存为pdf
  • 6、将爬取到的pdf转为一张长图片
  • 7、完整代码
    • 7.1、登录之前的准备
  • 8、也可以github上[自取](https://github.com/guiyang-yang/notes/blob/main/spider/get_wechat_article_pdf_and_photo.ipynb):
  • 上班搭地铁的时候太无聊了,想在微信看一些感兴趣的学习文章,却不知道如何精准查看。实在无聊的我,查询了一些学习资料,然后做了本期博客。本期博客主要的内容是根据自己输入的关键字,去搜狗微信爬取大量的文章,然后保存为pdf以及长图片,我再保存到手机慢慢看,哈哈哈。
  • 本期博客的代码基本是通用,只需要输入你要学习的内容的关键字,自定义保存pdf与长图片的路径,即可得到1000篇对应的公众号文章的pdf以及长图片。
  • 严正声明:本博客仅作学习教程,重在介绍如何使用各种便利的工具来达到学习的目的!不建议大家爬取太大的数据量的文章,虽然一次也最多爬取1000篇。
  • 2022-06-09,更新一下版本,新版本里不再需要鼠标的移动,也就是说爬取的过程中可以放在后台,可以使用鼠标干别的事情,大大提高了效率。

话不多说,让我步入正题。

1、搭建环境:Selenium+ChromeDriver+pyautogui

1.1 安装包

pip install selenium
pip install pyautogui

1.2、查看你的浏览器的版本

在网址栏输入:chrome://version

我的浏览器的版本是102.0.5005.63。

1.3、下载对应版本的ChromeDriver驱动

网址如下:http://chromedriver.storage.googleapis.com/index.html

因为我的谷歌版本是102.0.5005.63,所以我下载的ChromeDriver驱动对应的也是102.0.5005.63版本的。

1.4、设置环境变量(选做)

第一步:把下载好的zip压缩包解压,然后把里面的chromedriver.exe复制到谷歌浏览器的安装目录去。忘记谷歌浏览器的安装目录的人可以在1.2的图片那看可执行文件路径那里。

第二步:复制成功后,把这个目录复制一遍,添加到系统的环境变量里的path。

如果不想配置环境变量,也可以指定chromedriver.exe下载后所存放的位置。

1.5、暂时关闭浏览器设置中的“下载前询问每个文件的保存位置”

2、配置参数,使用驱动打开谷歌浏览器

运行工具:Jupyter NoteBook

from selenium import webdriver
import json
import time# 设置保存为pdf的参数
appState = """{"recentDestinations": [{"id": "Save as PDF","origin": "local"}],"mediaSize": {"height_microns": 279400,"name": "NA_LETTER","width_microns": 215900,"custom_display_name": "Letter"},"selectedDestinationId": "Save as PDF","version": 2,"isHeaderFooterEnabled": false
}"""# 设置pdf的保存路径
pdf_save_path = "D:\\Download\\pdf\\"appState = json.loads(appState)
profile = {'printing.print_preview_sticky_settings.appState': json.dumps(appState),'savefile.default_directory': pdf_save_path,'download.default_directory': pdf_save_path}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)# 该参数必须存在,不设置会无法使用打印,保存全屏图片等功能
chrome_options.add_argument('--kiosk-printing')# 用指定路径的ChromeDriver驱动去打开一个浏览器窗口
driver = webdriver.Chrome(executable_path="C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe",options=chrome_options)

其中,需要注意isHeaderFooterEnabled这个参数,如果为False,则为不打印页眉页脚的意思,因为我后面pdf转全屏图片的时候,存在页眉页脚会影响阅读,就取消了。然后executable_path是指定ChromeDriver驱动的所在位置,如果不指定,则默认是配置了环境变量的1.4中的环境变量里的路径:executable_path=“C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe”;最后是设置pdf所存放的位置,即需要手动指定pdf_save_path的位置。

3、扫码登录搜狗微信

import time# 登录搜狗微信
driver.get("https://weixin.sogou.com/")
time.sleep(3)
driver.find_elements_by_xpath('//a[@id="loginBtn"]')[0].click()

执行上面的代码时,会出现一个二维码,你需要使用微信扫码登录一下。注意,这一步非常重要,如果你没有扫码登录,那么很有可能在接下来爬取文章信息的时候会被检测出是爬虫,会弹出验证而导致爬取失败。而且你不登录,能爬取的学习文章才10页,登录的话可以爬取100页。

4、输入关键字,点击搜索按钮

比如我想学习一些关于selenium的文章,那么我就输入这个关键字就行

# 输入你要收集的学习文章的搜索关键字“XXX”
query = driver.find_element_by_name("query")
query.send_keys("selenium")# 点击搜索按钮
time.sleep(1)
driver.find_elements_by_xpath('//input[@uigs="search_article"]')[0].click()

5、爬取文章,并保存为pdf

def scroll_to_bottom(driver):js = "return action=document.body.scrollHeight"# 初始化现在滚动条所在高度为0height = 0# 当前窗口总高度new_height = driver.execute_script(js)while height < new_height:# 将滚动条调整至页面底部for i in range(height, new_height, 100):driver.execute_script('window.scrollTo(0, {})'.format(i))time.sleep(0.5)height = new_heighttime.sleep(2)new_height = driver.execute_script(js)title = driver.find_elements_by_xpath('//a[@uigs="article_title_{}"]'.format(0))[0].text.replace(" ","-")
driver.find_elements_by_xpath('//a[@uigs="article_title_{}"]'.format(0))[0].click()
driver.switch_to.window(driver.window_handles[1])
time.sleep(2)
scroll_to_bottom(driver)
driver.execute_script('document.title="{}";window.print();'.format(title))
time.sleep(2)
driver.close()
driver.switch_to.window(driver.window_handles[0])

6、将爬取到的pdf转为一张长图片

import fitz  # fitz就是pip install PyMuPDF
import os
import glob
from PIL import Imagedef pdf_to_pages_photo(pdfPath, imagePath, split_name):pdf_context = fitz.open(pdfPath)for pg in range(pdf_context.pageCount):page = pdf_context[pg]rotate = int(0)# 每个尺寸的缩放系数为1.3,这将为我们生成分辨率提高2.6的图像。# 此处若是不做设置,默认图片大小为:792X612, dpi=96zoom_x = 1.33333333  # (1.33333333-->1056x816)   (2-->1584x1224)zoom_y = 1.33333333mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)pix = page.getPixmap(matrix=mat, alpha=False)if not os.path.exists(imagePath):  # 判断存放图片的文件夹是否存在os.makedirs(imagePath)  # 若图片文件夹不存在就创建pix.writePNG(imagePath + '{}{}.png'.format(split_name,str(pg+1)))  # 将图片写入指定的文件夹内def pages_photo_APhoto(path,split_photo_name,title):page_photo_list = []image_list = []page_photo_list = glob.glob('{}{}*.png'.format(path,split_photo_name))page_photo_list = [fn.replace(path,'') for fn in page_photo_list]# 文件夹名 按数字排序page_photo_list.sort(key=lambda x: int(x[len(split_photo_name):-4]))for pphoto in page_photo_list:image_list.append(Image.open(path + os.sep + pphoto))width = 0height = 0for img in image_list:# 单幅图像尺寸w, h = img.sizeheight += h# 取最大的宽度作为拼接图的宽度width = max(width, w)# 创建空白长图result = Image.new(image_list[0].mode, (width, height), 0xffffff)# 拼接图片height = 0for img in image_list:w, h = img.size# 图片水平居中result.paste(img, box=(round(width / 2 - w / 2), height))height += h# 保存图片result.save('{}{}.png'.format(path,title),quality=95)# 删除那些片段化的图片,因为已经合成了长图片了for pphoto in page_photo_list:os.remove(path+pphoto)time.sleep(1)# 定义图片存放的位置
imagePath = 'D:\\Download\\photo\\'# 这是刚刚爬取的pdf的下载路径
pdfPath =  pdf_save_path+title+'.pdf'#将pdf转化为图片,是按页转换
split_photo_name = 'images_'
pdf_to_pages_photo(pdfPath, imagePath, split_photo_name)# 将按页转换的图片转化为一张长图片,并删除多余的图片
page_title = os.path.split(pdfPath)[1].replace('.pdf','')
pages_photo_APhoto(imagePath,split_photo_name,page_title)

在代码中,需要注意存放图片的绝对路径,这个自己随便定义就行,一般我建议放在与保存pdf相近的地方,这样方便全选发到手机在挤地铁无聊的时候学习一下。

至此,所有的注意事项基本都说了,如果大家按照我的介绍去一步步执行,那么你就可以得到一个pdf以及对应的长屏图片。

7、完整代码

通过上面1-6节的介绍。如果有正确运行,通过观察selenium操作的谷歌浏览器的运行页面,相信大家已经知道整体的流程以及步骤是怎么实现的了,现在我分享一下实现的步骤以及其完整的代码。ps:可以爬取到1000篇学习文章的那种,虽然爬取1000篇可能需要1个小时以上。

7.1、登录之前的准备

自定义pdf_save_path,修改为自己想要存储的路径

from selenium import webdriver
import json
import time# 设置保存为pdf的参数
appState = """{"recentDestinations": [{"id": "Save as PDF","origin": "local"}],"mediaSize": {"height_microns": 279400,"name": "NA_LETTER","width_microns": 215900,"custom_display_name": "Letter"},"selectedDestinationId": "Save as PDF","version": 2,"isHeaderFooterEnabled": false
}"""# 设置pdf的保存路径
pdf_save_path = "D:\\Download\\pdf\\"appState = json.loads(appState)
profile = {'printing.print_preview_sticky_settings.appState': json.dumps(appState),'savefile.default_directory': pdf_save_path,'download.default_directory': pdf_save_path}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)# 该参数必须存在,不设置会无法使用打印,保存全屏图片等功能
chrome_options.add_argument('--kiosk-printing')# 用指定路径的ChromeDriver驱动去打开一个浏览器窗口
driver = webdriver.Chrome(executable_path="C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe",options=chrome_options)# 登录搜狗微信
driver.get("https://weixin.sogou.com/")
time.sleep(3)
driver.find_elements_by_xpath('//a[@id="loginBtn"]')[0].click()

微信扫码登录之后,更改**图片的存放路径(imagePath)**为符合自己电脑真实情况,然后静等1个多分钟就可以得到1000页学习文章了。

def scroll_to_bottom(driver):js = "return action=document.body.scrollHeight"# 初始化现在滚动条所在高度为0height = 0# 当前窗口总高度new_height = driver.execute_script(js)while height < new_height:# 将滚动条调整至页面底部for i in range(height, new_height, 100):driver.execute_script('window.scrollTo(0, {})'.format(i))time.sleep(0.5)height = new_heighttime.sleep(2)new_height = driver.execute_script(js)def get_pdf(n):for i in range(n):for j in range(10):title = driver.find_elements_by_xpath('//a[@uigs="article_title_{}"]'.format(j))[0].text.replace(" ","-") driver.find_elements_by_xpath('//a[@uigs="article_title_{}"]'.format(j))[0].click()driver.switch_to.window(driver.window_handles[1])time.sleep(2)scroll_to_bottom(driver)driver.execute_script('document.title="{}";window.print();'.format(title))time.sleep(2)driver.close()driver.switch_to.window(driver.window_handles[0])time.sleep(2)def pdf_to_pages_photo(pdfPath, imagePath, split_name):pdf_context = fitz.open(pdfPath)for pg in range(pdf_context.pageCount):page = pdf_context[pg]rotate = int(0)# 每个尺寸的缩放系数为1.3,这将为我们生成分辨率提高2.6的图像。# 此处若是不做设置,默认图片大小为:792X612, dpi=96zoom_x = 1.33333333  # (1.33333333-->1056x816)   (2-->1584x1224)zoom_y = 1.33333333mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)pix = page.getPixmap(matrix=mat, alpha=False)if not os.path.exists(imagePath):  # 判断存放图片的文件夹是否存在os.makedirs(imagePath)  # 若图片文件夹不存在就创建pix.writePNG(imagePath + '{}{}.png'.format(split_name,str(pg+1)))  # 将图片写入指定的文件夹内def pages_photo_APhoto(path,split_photo_name,title):page_photo_list = []image_list = []page_photo_list = glob.glob('{}{}*.png'.format(path,split_photo_name))page_photo_list = [fn.replace(path,'') for fn in page_photo_list]# 文件夹名 按数字排序page_photo_list.sort(key=lambda x: int(x[len(split_photo_name):-4]))for pphoto in page_photo_list:image_list.append(Image.open(path + os.sep + pphoto))width = 0height = 0for img in image_list:# 单幅图像尺寸w, h = img.sizeheight += h# 取最大的宽度作为拼接图的宽度width = max(width, w)# 创建空白长图result = Image.new(image_list[0].mode, (width, height), 0xffffff)# 拼接图片height = 0for img in image_list:w, h = img.size# 图片水平居中result.paste(img, box=(round(width / 2 - w / 2), height))height += h# 保存图片result.save('{}{}.png'.format(path,title),quality=95)# 删除那些片段化的图片,因为已经合成了长图片了for pphoto in page_photo_list:os.remove(path+pphoto)time.sleep(1)if __name__ == "__main__":# 1、文本框中输入你要收集的学习文章的搜索关键字“XXX”,本次案例设置搜索词为seleniumquery = driver.find_element_by_name("query")query.send_keys("selenium")# 2、点击搜索按钮time.sleep(1)driver.find_elements_by_xpath('//input[@uigs="search_article"]')[0].click()# 3、打印了所有的目标pdf,最多100页,如果不先扫码登录,最多就只能爬取10页get_pdf(1)# 4、获取刚刚爬取的所有pdf的存放路径list_pdf = glob.glob(pdf_save_path+'*.pdf')# 5、定义储存图片的目录imagePath = 'D:\\Download\\photo\\'for pdf in list_pdf:# 6、循环得到的每一个PDF地址pdfPath = pdf# 7、将pdf转化为图片,是按页转换split_photo_name = 'images_'pdf_to_pages_photo(pdfPath, imagePath, split_photo_name)# 8、将按页转换的图片转化为一张长图片,并删除多余的图片title = os.path.split(pdf)[1].replace('.pdf','')pages_photo_APhoto(imagePath,split_photo_name,title)

8、也可以github上自取:

创作不易,如果这篇博客有帮助到你,麻烦你帮忙点个赞+收藏再走。

Selenium 爬取微信公众号文章并保存为pdf与长图片(2022-06-09更新版)相关推荐

  1. python爬取正确但不出文件_使用Python爬取微信公众号文章并保存为PDF文件(解决图片不显示的问题)...

    前言 第一次写博客,主要内容是爬取微信公众号的文章,将文章以PDF格式保存在本地. 爬取微信公众号文章(使用wechatsogou) 1.安装 pip install wechatsogou --up ...

  2. (Java篇)爬取微信公众号文章并保存为 PDF 格式

    前言 背景: 某一天,拿着自己的手机看着技术文章,然而手机看技术文章,有时候确实蛋疼,因为一旦代码多起来,小屏幕看的还是眼花:又或者某一天觉得这一篇文章,觉得写的很棒棒哦,于是先收藏,打算过几天看,然 ...

  3. python批量保存网页为pdf_爬取微信公众号文章并保存为PDF文件(Python方法)

    {title} {content_info['content_html']}

  4. python爬取论文代码_Python selenium爬取微信公众号文章代码详解

    需求: 想阅读微信公众号历史文章,但是每次找回看得地方不方便. 思路: 1.使用selenium打开微信公众号历史文章,并滚动刷新到最底部,获取到所有历史文章urls. 2.对urls进行遍历访问,并 ...

  5. python爬虫爬取公众号_Python selenium爬取微信公众号文章代码详解

    需求: 想阅读微信公众号历史文章,但是每次找回看得地方不方便. 思路: 1.使用selenium打开微信公众号历史文章,并滚动刷新到最底部,获取到所有历史文章urls. 2.对urls进行遍历访问,并 ...

  6. python 爬取微信公众号文章(selenium+webdriver)

    """通过搜狗搜索中的微信搜索入口爬取微信公众号文章(selenium) """ import re import os import js ...

  7. python爬取微信公众号文章(包含文章内容和图片)

    之前虽然做过网页爬取,但微信爬取一直没做过,因为我一直不知道网页可以进微信公众平台,只用过微信客户端进微信公众号.既然可以通过网页进微信公众平台,那么爬取微信公众号文章就流程上就没太多难度了. 自己在 ...

  8. Python爬取微信公众号文章、点赞数

    代码还是热乎的,只要你细心一步步的慢慢调试,绝壁没问题 前期准备 订阅号: Python: Fiddler: 微信账号: 流程 使用用微信公众号生成cookie 使用Fiddler抓取微信公众号数据, ...

  9. 使用代理爬去微信公众号_Python3网络爬虫开发实战之使用代理爬取微信公众号文章...

    本节目标 我们的主要目标是利用代理爬取微信公众号的文章,提取正文.发表日期.公众号等内容,爬取来源是搜狗微信,其链接为 http://weixin.sogou.com/,然后把爬取结果保存到 MySQ ...

  10. 使用代理爬去微信公众号_Python3WebSpider/9.5-使用代理爬取微信公众号文章.md at master · Lainton/Python3WebSpider · GitHub...

    9.5 使用代理爬取微信公众号文章 前面讲解了代理池的维护和付费代理的相关使用方法,接下来我们进行一下实战演练,利用代理来爬取微信公众号的文章. 1. 本节目标 我们的主要目标是利用代理爬取微信公众号 ...

最新文章

  1. ad域控如何建立在云端_呼叫中心哪家好?选择云端呼叫中心还是本地化部署呼叫中心好?...
  2. 测验3: 基本数据类型 (第3周)
  3. 品牌到底要不要做全渠道?且听他们怎么说……
  4. linux为什么创建不了分区,linux下扩容磁盘扩展分区解决因无法创建新分区不能扩容lvm问题...
  5. 去掉chrome、safari input或textarea在得到焦点时出现黄色边框的方法
  6. 第十章:在Spark集群上掌握比较重要的图操作之Computing Degree
  7. VMware vSphere “I moved it” or “I copied it” – What’s the difference?
  8. APP移动测试用例总结
  9. 一点Python学习资源
  10. Java中String, StringBuilder和StringBuffer
  11. Ubuntu查看网速工具
  12. 【一句日历】2019年7月
  13. 西电微机系统课程设计步进电机开环控制系统
  14. 分享一套国产化技术开发JAVA语言,大佬手下留情
  15. 国产折叠屏手机:华为领航,跟随者众
  16. 【kmp】似乎在梦中见过的样子
  17. 交换机vlan配置实训心得_交换机与路由器的实训心得
  18. SumGNN部署实验lmdb.ReadonlyError: mdb_dbi_open: Permission denied
  19. Go 中 Gzip 与 json 搭配使用压缩数据,减少数据传输量
  20. 基于JavaScript的简易计算器(可处理连续加减乘除运算)

热门文章

  1. 惠普暗影2 pro ubuntu16.04安装nvidia显卡驱动
  2. java毕业设计源码介绍 基于SSM美好生活九宫格日志网日记网站
  3. 怎样在计算机桌面上安装驱动器,如何安装电脑设备驱动程序?
  4. 微软win2008停止服务器,微软停止技术支持Windows Server 2008/2008 R2
  5. 黑莓9900 刷机体验(ROM:7.1.0.318_DoCoMo_Japan版)
  6. 肥学献礼——自动写诗
  7. 定时上传文件至ftp服务器,CuteFTP FTP文件的定时上传图文教程
  8. qq连连看分析编写简单辅助
  9. oo结尾的单词发音规律
  10. 无人机-4无人机结构设计