首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用美汤从网站抓取数据并在jinja2中显示

用美汤从网站抓取数据并在jinja2中显示
EN

Stack Overflow用户
提问于 2012-12-18 14:46:51
回答 1查看 571关注 0票数 1

我正在尝试使用Beautiful Soup从网站上拉取数据列表:

代码语言:javascript
复制
class burger(webapp2.RequestHandler):
    Husam = urlopen('http://www.qaym.com/city/77/category/3/%D8%A7%D9%84%D8%AE%D8%A8%D8%B1/%D8%A8%D8%B1%D8%AC%D8%B1/').read()

    def get(self, soup = BeautifulSoup(Husam)):

        tago = soup.find_all("a", class_ = "bigger floatholder")
        for tag in tago:
        me2 = tag.get_text("\n")

        template_values = {
                           'me2': me2
                           }
        for template in template_values:

            template = jinja_environment.get_template('index.html')
            self.response.out.write(template.render(template_values))

现在,当我尝试使用jinja2在模板中显示数据时,它是根据列表的数量重复整个模板,并将每个单独的信息放在一个模板中。

我如何将整个列表放在一个标签中,并能够编辑其他标签而不重复?

代码语言:javascript
复制
<li>{{ me2}}</li>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-09 13:23:19

要输出条目列表,可以在jinja2模板中循环遍历它们,如下所示:

代码语言:javascript
复制
{%for entry in me2%}
  <li> {{entry}} </li>
{% endfor %}

要使用它,您的python代码还必须将标记放入列表中。

像这样的东西应该是有效的:

代码语言:javascript
复制
   def get(self, soup=BeautifulSoup(Husam)):
      tago = soup.find_all("a", class_="bigger floatholder")

      # Create a list to store your entries
      values = []

      for tag in tago:
          me2 = tag.get_text("\n")
          # Append each tag to the list
          values.append(me2)

      template = jinja_environment.get_template('index.html')

      # Put the list of values into a dict entry for jinja2 to use
      template_values = {'me2': values}

      # Render the template with the dict that contains the list
      self.response.out.write(template.render(template_values))

参考文献:

  • Jinja2 template documentation
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13927719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档