更简单的python客户端库

zester的Python项目详细描述


Zester是一个库,它使为没有API的网站开发Python客户端变得更加容易。

没有lxml,没有xpath,只有javascript。

通过将以下代码保存在名为hnclient.py的文件中,让我们为Hacker News创建一个客户机库:

from zester import MultipleClient, Attribute

class HNClient(MultipleClient):
    url = "http://news.ycombinator.com/"
    title = Attribute(selector="$('.title a')", modifier="$(el).html()")
    link = Attribute(selector="$('.title a')"), modifier="$(el).attr('href')")
    points = Attribute(selector="$('.subtext span')", modifier="$(el).html().replace(' points', '')")

现在,让我们用我们刚做的客户。打开python外壳:

>>> from hnclient import HNClient
>>> client = HNClient()
>>> stories = client.process()
>>> stories[0]
HNClientResponse(points=u'200', link=u'http://daltoncaldwell.com/what-twitter-could-have-been', title=u'What Twitter could have been')
>>> print stories[0].title
What Twitter could have been
>>> print stories[0].link
http://daltoncaldwell.com/what-twitter-could-have-been
>>> print stories[0].points
56

我们在那里细分了multipleclient,因为我们计划返回多个结果。如果我们想为返回一个结果的Weather.gov之类的东西创建一个客户机,我们可以这样做:

from zester import SingleClient, Attribute

class WeatherClient(SingleClient):
    url = "http://forecast.weather.gov/MapClick.php?lat={lat}&lon={lng}"
    temperature = Attribute(selector="$('.myforecast-current-lrg').html()")
    humidity = Attribute(selector="$('.current-conditions-detail li').contents()[1]")
    heat_index = Attribute(selector="$('.current-conditions-detail li').contents()[11]")

    def __init__(self, lat, lng, *args, **kwargs):
        super(WeatherClient, self).__init__(*args, **kwargs)
        self.url = self.url.format(lat=lat, lng=lng)

这还演示了如何允许获取参数:

>>> from weather_client import WeatherClient
>>> client = WeatherClient(lat=40.7143528, lng=-74.0059731)
>>> curr_weather = client.process()
>>> curr_weather
WeatherClientResponse(heat_index=u'82\xb0F (28\xb0C)', temperature=u'80\xb0F', humidity=u'58%')
>>> print curr_weather.temperature
80°F
>>> print curr_weather.humidity
58%
>>> print curr_weather.heat_index
82°F (28°C)

安装

泽斯特依赖于Ghost.py。在安装Zester之前必须安装它。ghost.py还需要安装pyqt或pyside。

安装ghost.py后,要安装Zester:

$ pip install zester

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何格式化servlet响应以生成HTML中“accept”参数可接受的媒体类型?   java如何使用JasperReports为单个报表传递多个结果集?   EclipseVBA到JAVA链接   java如何为Gradle中的不同配置配置PMD规则集?   在给出正确答案之前,是否要求回答?Java Eclipse   java查询SearchView崩溃(尝试实现SearchView操作栏)   java为什么跳过我的IF语句?   java循环以获取与输入值最接近的对象   java默认构造函数真正做什么?   java我需要测试类中的测试方法吗   java如何在代码中滚动滚动窗格?   java我需要获得发布和调试证书指纹的帮助   javascript如何在JS中取消Java“DES/CBC/PKCS5Padding”?