python 怎么给原有模块添加自定义方法?

2016-10-10 13:34:12 +08:00
 vtoexsir

from bs4 import BeautifulSoup as bs soup=bs(html_code) #伪代码 text=soup.get_text() #这个 get_text()方法是 bs 定义好了的方法 my_text=soup.my_get_text() #这个 my_get_text()方法是 bs 没有的方法,会报异常

如上代码,比如 bs 中本来没有 my_get_text()这个方法,我是否可以写一个自定义模块,比如叫做'my_bs',

import my_bs

当如上导入自定义的模块后, 就能正常运行如下代码:my_text=soup.my_get_text() 说白了,我就是想给已有的 bs4 包添加一个我自己定义的方法. 但是不是通过修改 bs4 的源代码,而是自定义一个模块, 在自己的代码中导入自定义模块来达到目的. 多谢!

2108 次点击
所在节点    Python
6 条回复
masterzh01
2016-10-10 13:38:35 +08:00
masterzh01
2016-10-10 13:39:19 +08:00
clino
2016-10-10 13:41:04 +08:00
如果是类就继承派生一个新类来用是不是就行了
yangtukun1412
2016-10-10 13:41:36 +08:00
monkey patch.
ty89
2016-10-10 13:56:25 +08:00
import some_module

class PatchedClass(object):
...

some_module.TheClass = PatchedClass
vtoexsir
2016-10-10 19:36:26 +08:00
新建 myBS.py 文件,内容如下:
import bs4


def getTextWithoutScript(self, separator=u"", strip=False,
withoutScript=True, withoutComment=True):
"""获取网页文本,不包含 html 源码中的 script 脚本的内容"""
return separator.join([s for s in self._all_strings(strip) if s.parent.name.lower() != 'script'])


bs4.Tag.getTextWithoutScript = getTextWithoutScript

使用方法:
首先导入 myBS.py,其他使用方法就是直接调用,与 bs 的原生方法一样:
import myBS
from bs4 import BeautifulSoup as bs

s=bs(html_code,'html5lib')
s.getTextWithoutScript()

不方便的地方:在 pycharm 下该新加入 BS 的方法不能智能提示!
感谢诸位老师!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/311607

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX