python - 使用 Beautiful Soup 从网站抓取数据并在 jinja2 中显示

标签 python google-app-engine beautifulsoup jinja2

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

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 在模板中显示数据时,它会根据列表的数量重复整个模板,并将每个信息放入一个模板中。

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

<li>{{ me2}}</li>

最佳答案

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

{%for entry in me2%}
  <li> {{entry}} </li>
{% endfor %}

要使用此功能,您的 Python 代码还必须将标签放入列表中。

这样的事情应该有效:

   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))

引用文献:

关于python - 使用 Beautiful Soup 从网站抓取数据并在 jinja2 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13927719/

相关文章:

python - 根据最后一行获取新值并检查 ID

python - 使用字典将一个列表转换为另一个列表的最Pythonic方法?

google-app-engine - 如何为 google-app-engine 设置 SSL 模块?

python - 谷歌应用引擎 : Error in bulkloader. yaml

python - 使用 BeautifulSoup 从 HTML 创建 JSON 结构

python - 如何使用 BeautifulSoup 将平面 HTML 结构解析为字典?

python - NumPy 中的 ndarray 和数组有什么区别?

python - 从 CSV 复制到 SQL 时丢失数据

java - Google App Engine 数据存储区中的赞成票和反对票设计

python - 通过检查 int 范围替换文本