声明式超文本客户端
Peppertext的Python项目详细描述
声明性超文本客户端
安装
pip install peppertext
概述
frompeppertextimportHypertext,SimpleURLField,resolve,register,selector@registerclassGoogleBlogPage(Hypertext):url=SimpleURLField("https://googleblog.blogspot.kr/{year}/{month}/{title}.html")title=selector.find(".title[itemprop=name]").text()body=selector.find(".post-body").text()
它将给定的头、url和查询字符串解析为超文本对象。
>>>p=resolve("https://googleblog.blogspot.kr/2015/11/google-gobble-thanksgiving-trends-on.html")>>>p<GoogleBlogPageat0x108a4d1f0>>>>p.fetch()>>>p['title']'Google gobble: Thanksgiving trends on Search'>>>p['body']'In just a few hours, people across the U.S. will be settling...'
您可以使用声明为 类中的字段。
>>>p=GoogleBlogPage(...year="2015",...month="11",...title="google-gobble-thanksgiving-trends-on"...)>>>p.fetch()>>>p['title']'Google gobble: Thanksgiving trends on Search'
选择器
classGoogleBlogPage(Hypertext):# ...title=selector.find(".title[itemprop=name]").text()# ...
选择器处理从服务器返回作为响应的文档。 在上面的示例中,选择器解析文档并 查找用“指定的元素。title[itemprop=name]css选择器。 您可以通过订阅googleblogpage对象来访问值title 使用选择器名称。
document=pq("""<div> <a href="http://example.com">Link1</a> <a href="http://example.com/dahokan">Link2</a> <a href="http://example.com/manoha">Link3</a> </div>""")find_selector=selector.find('a')selected_els=find_selector.select(document)self.assertEqual([pq(el).attr["href"]forelinselected_els],["http://example.com","http://example.com/dahokan","http://example.com/manoha"])
查找
选择与给定css选择器字符串匹配的html元素。
属性
获取具有给定属性名的元素的属性值。
文本
选择HTML元素的内部文本值。
位于
在索引中获取项目
sub
sub_selector=selector.sub(pattern="\d+",repl="")
做正则表达式替换。
演员
int_cast_selector=selector.cast(int)
将数据传递给作为参数给定的函数。
兼容性
PepperText支持Python2.7和3。
开发中的功能
- 用于分析错误处理的接口
- 对页面选择器的多态访问
- 用于解析和遍历页面中链接的界面