python 获取 模块 class 中所有方法

写个方法去获取一个模块包含模块中的所有公共方法 

#coding:utf-8
import keywords
import inspect

func_list = []        

def class_loader(cls):
    _class = getattr(keywords,cls)
    return _class()

def get_kw_list():
    for m in keywords.__all__:
        _class = class_loader(m)
        for name,value in inspect.getmembers(_class):
            if not name.startswith("_"):
                func_list.append(name)
    return func_list

print get_kw_list()

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/Jasonliujintao/article/details/77449977


 反射机制的工厂方法?反射机制的策略模式?

import sys
 
def func1():
	print('func1')
 
class TestClass():
	def p(self):
		print('you got me!')
 
def Main():
	className = 'TestClass'
	funcName = 'func1'
 
	testClass = globals()[className]()
	testClass.p()
	
	testFunc = globals()[funcName]
	testFunc()
 
Main()

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Python查找HTML特定class的元素,可以使用第三方库如BeautifulSoup或使用内置模块如`html.parser`。以下是使用不同方法查找的示例代码: 使用BeautifulSoup库: ```python from bs4 import BeautifulSoup html = """ <html> <head> <title>示例</title> </head> <body> <div class="container"> <h1>标题1</h1> <p class="text">这是一段文本。</p> </div> <div class="container"> <h1>标题2</h1> <p class="text">这是另一段文本。</p> </div> </body> </html> """ soup = BeautifulSoup(html, 'html.parser') # 使用find_all方法查找class为"text"的元素 elements = soup.find_all(class_="text") # 打印查找到的元素文本内容 for element in elements: print(element.text) ``` 使用内置模块`html.parser`: ```python from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): if tag == "p": for attr in attrs: if attr[0] == "class" and "text" in attr[1]: self.found_text = True def handle_data(self, data): if self.found_text: print(data) self.found_text = False html = """ <html> <head> <title>示例</title> </head> <body> <div class="container"> <h1>标题1</h1> <p class="text">这是一段文本。</p> </div> <div class="container"> <h1>标题2</h1> <p class="text">这是另一段文本。</p> </div> </body> </html> """ parser = MyHTMLParser() parser.feed(html) ``` 这些代码都会输出: ``` 这是一段文本。 这是另一段文本。 ``` 使用BeautifulSoup库时,我们创建了一个BeautifulSoup对象,并将HTML文档和解析器类型传递给它。然后,我们使用`find_all`方法并指定`class_`参数为目标class的名称来查找元素。最后,遍历查找到的元素并使用`.text`属性获取其文本内容。 使用内置模块`html.parser`时,我们创建了一个自定义的HTML解析器类,继承自`HTMLParser`,并重写了`handle_starttag`和`handle_data`方法。在`handle_starttag`方法,我们检查标签是否为`<p>`,如果是,则检查其属性是否包含目标class的名称。在`handle_data`方法,如果之前找到了目标class的开始标签,我们打印出其文本内容。然后,我们使用自定义解析器类的实例,并调用其`feed`方法来解析HTML文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值