selenium python文档_selenium+python实现百度文库word文档抓取

 2023-09-15 阅读 31 评论 0

摘要:更新这个代码最近又改了一点,另外和其他一些小程序一起放在了一个jupyter notebook里,现在挂在github上面。github现在对jupyter notebook的支持非常的好,甚至可以直接在网上运行。不过这个例子涉及了selenium,所以是没法在github上面跑起来就是了

更新这个代码最近又改了一点,另外和其他一些小程序一起放在了一个jupyter notebook里,现在挂在github上面。github现在对jupyter notebook的支持非常的好,甚至可以直接在网上运行。不过这个例子涉及了selenium,所以是没法在github上面跑起来就是了。github页面地址:https://github.com/beneon/smallTools​github.comv2-9e561bccbce897fedcd66b051d144ea3_ipico.jpg

原先的文章:https://talkpython.fm/episodes/show/142/automating-the-web-with-selenium-and-instapy​talkpython.fm

pycharm和python区别?我是最近听podcast 的时候发现这个东西的。简单来说是一个帮你在网页上面点来点去的机器人。InstaPy是用了这个框架来爬instagram,这个比较高大上。我这种水平只希望能用selenium帮忙爬一下百度文库。

百度文库的ppt是没的说的,毕竟已经全部转成了图片,爬也是白瞎。但是我不想再一些Word文档上面浪费我的点数啊。以前用javascript结合autohotkey,勉强能用:路人乙小明:百度文库word文档抓取naive实现​zhuanlan.zhihu.comv2-57cb90ced0ff18ac50418f9355296636_180x120.jpg

今天试了试selenium,也可以实现类似的需求,关键这次完全不用任何鼠标操作了。

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

import re

browser = webdriver.Chrome()

browser.get('https://wenku.baidu.com/view/xxxlorem ipsumxxxx.html')

这一段是导入selenium,打开一个chrome浏览器webdriver,这个webdriver需要自己额外下载放到python的目录里面。具体操作参见:1. Installation - Selenium Python Bindings 2 documentation​selenium-python.readthedocs.io

上面的是selenium python版本的用法,除了driver的安装还有很多其他有用的内容,自己看去。

pageInput = browser.find_element_by_class_name("page-input")

pageInput.clear()

pageInput.send_keys("1")

pageInput.send_keys(Keys.RETURN)

elem = browser.find_elements_by_class_name("reader-page")[0]

subelems = elem.find_elements_by_class_name("reader-word-layer")

这里是转到第1页,顺便获取第一页下面的所有reader-word-layer类div。这个class的名称,包括前面的reader-page自己用chrome分析一下百度文库的文档就知道了。

# 行融合部分开始

print(lineMerging(subelems))

# 这个是引用行融合

reTopVal = re.compile(r'top: (\d+)px')

def getYpos(e):

"""获取一个字符block的style里面的top属性,相关的regex在函数外面已经compile完成"""

mo = reTopVal.search(e.get_attribute('style'))

return mo.group(1)

def lineMerging(elems):

"""根据位置top信息判断是否属于一行,如果是新的一行加上换行符以后再连接文字"""

topTemp = ""

rstString = ""

for e in elems:

if topTemp == getYpos(e):

rstString += e.text

else:

topTemp = getYpos(e)

rstString += '\n' + e.text

rstString=rstString.replace('\n','{newline}')

rstString=rstString.replace('\n','')

rstString=rstString.replace('{newline}','\n')

return rstString

每一个reader-word-layer的div都有一个style属性,里面标明了这个div的top属性。同一行的文本top都一样,所以根据top可以将同行的div内文字合并。

另外和pdf一样,会有硬换行。百度文库的特点是,如果是真的换行,是‘ \n’(两个空格加一个换行符),而硬换行则是单纯的'\n'。所以比较蠢的办法就是做三次全局文本替换……

上面的代码我在jupyter notebook里面跑过没什么大问题

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/58513.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息