【问题标题】:meaning of " for a in html('.l')" in python“for a in html('.l')”在python中的含义
【发布时间】:2018-08-02 02:14:04
【问题描述】:

我一直在看howdoi的源代码。 https://github.com/gleitz/howdoi

这里的 extract_links_from_bing 和 extract_links_from_google 有这种语法。

我尝试在线搜索与 xml、元素树相关的所有内容,但在任何地方都找不到类似构造函数的语法。

这里是函数

def _extract_links_from_bing(html):
    html.remove_namespaces()
    return [a.attrib['href'] for a in html('.b_algo')('h2')('a')]


def _extract_links_from_google(html):
    return [a.attrib['href'] for a in html('.l')] or \
    [a.attrib['href'] for a in html('.r')('a')]

我的问题是html('.b_algo')('h2')('a') 是如何迭代的。任何与类似语法相关的链接将不胜感激。

感谢阅读。

【问题讨论】:

    标签: python pyquery


    【解决方案1】:

    那个项目使用的是PyQuery,而不是xml etree。

    注意html 来自_get_links()

    def _get_links(query):
        search_engine = os.getenv('HOWDOI_SEARCH_ENGINE', 'google')
        search_url = _get_search_url(search_engine)
    
        result = _get_result(search_url.format(URL, url_quote(query)))
        html = pq(result)
        return _extract_links(html, search_engine)
    

    pq 来自这里:

    from pyquery import PyQuery as pq
    

    PyQuery 对象可以像 jquery 中的 $ 一样使用。这是您所指的 函数调用 语法。

    来自他们的快速入门:

    >>> d("#hello")
    [<p#hello.hello>]
    >>> p = d("#hello")
    >>> print(p.html())
    Hello world !
    >>> p.html("you know <a href='http://python.org/'>Python</a> rocks")
    [<p#hello.hello>]
    >>> print(p.html())
    you know <a href="http://python.org/">Python</a> rocks
    >>> print(p.text())
    you know Python rocks
    

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 2016-04-14
      • 2015-02-20
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      相关资源
      最近更新 更多