更简单的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以编程方式最小化JInternalFrame?   java使用JsonPath将不均匀列表提取为类型化对象   spring如何将java/resources文件获取到InputStream?   Java逻辑错误并不总是存在   java Firebase,更新特定字段   Java stream groupby并同时加入以进行csv导出   java安卓:如果出现任何声音,监听器将录制声音   java如何从多个文件中轮询最后修改的文件并发送到apache camel中的目标端点?   java是否返回多个比较器?   JavaBean IO:Date MMM在CAPS中不解析   当JButton从另一个类单击时,java正在更新JLabel   基类中子类的Java泛型初始化   jakarta ee Java ee制作一个以毫秒为间隔的计时器来发送数据包   json Windows Azure日期格式转换为Java日期