首页 > 解决方案 > 如何使用一个“for循环”从视图中渲染图像、标题和到模板的链接

问题描述

我正在抓取http://books.toscrape.com/catalogue/page-1.html并且我想返回引导卡中前 10 本书的图像标题评级价格。下面的代码只返回标题。我的重点是在一个for循环中渲染图像、标题和链接

import requests
from bs4 import BeautifulSoup


r = requests.get("http://books.toscrape.com/catalogue/page-1.html")
soup = BeautifulSoup(r.content, 'html5lib')

book = soup.findAll('h3')


book_list = []

for title in book [:10]:
    book_list.append(title.text)


def index(req):
    return render(req, 'books/index.html', {'book_list': book_list})


这是引导卡。

{% for title in book_list %}
<div class="card" style="width: 18rem;">
    <img class="card-img-top" src="{{image}}" alt="Card image cap">
        <div class="card-body">
            <h5 class="card-text">{{title}}.</h5>
            <p class="card-text">{{rating}}.</p>
            <h5 class="card-text">{{price}}.</h5>
            <a href="url"><h6>{{link}} </h6></a>
        </div>
</div>
{% endfor %}

如何for在 HTML 模板中看到的单个循环中呈现书籍的所有元数据?我以类名为“product_pod”的卡为目标并提取详细信息。

标签: python-3.xweb-scrapingbeautifulsouppython-requests

解决方案


这应该可以帮助您:

import requests
from bs4 import BeautifulSoup


r = requests.get("http://books.toscrape.com/catalogue/page-1.html")
soup = BeautifulSoup(r.content, 'html5lib')

li_tags = soup.find_all('li', class_ = "col-xs-6 col-sm-4 col-md-3 col-lg-3")[:10]

for li in li_tags:

    print('-'*100)
    
    img = "http://books.toscrape.com/"+ li.article.div.a.img['src'][2:]
    print(f"Image link = {img}")

    title = li.article.h3.a['title']
    print(f"Title = {title}")

    rating = li.article.p['class'][-1]
    print(f"Rating = {rating} Star(s)")

    price = li.article.find('div', class_ = "product_price").p.text
    print(f"Price = {price}")

输出:

----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg
Title = A Light in the Attic
Rating = Three Star(s)
Price = £51.77
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/26/0c/260c6ae16bce31c8f8c95daddd9f4a1c.jpg
Title = Tipping the Velvet
Rating = One Star(s)
Price = £53.74
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/3e/ef/3eef99c9d9adef34639f510662022830.jpg
Title = Soumission
Rating = One Star(s)
Price = £50.10
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/32/51/3251cf3a3412f53f339e42cac2134093.jpg
Title = Sharp Objects
Rating = Four Star(s)
Price = £47.82
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/be/a5/bea5697f2534a2f86a3ef27b5a8c12a6.jpg
Title = Sapiens: A Brief History of Humankind
Rating = Five Star(s)
Price = £54.23
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/68/33/68339b4c9bc034267e1da611ab3b34f8.jpg
Title = The Requiem Red
Rating = One Star(s)
Price = £22.65
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/92/27/92274a95b7c251fea59a2b8a78275ab4.jpg
Title = The Dirty Little Secrets of Getting Your Dream Job
Rating = Four Star(s)
Price = £33.34
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/3d/54/3d54940e57e662c4dd1f3ff00c78cc64.jpg
Title = The Coming Woman: A Novel Based on the Life of the Infamous Feminist, Victoria Woodhull
Rating = Three Star(s)
Price = £17.93
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/66/88/66883b91f6804b2323c8369331cb7dd1.jpg
Title = The Boys in the Boat: Nine Americans and Their Epic Quest for Gold at the 1936 Berlin Olympics
Rating = Four Star(s)
Price = £22.60
----------------------------------------------------------------------------------------------------
Image link = http://books.toscrape.com//media/cache/58/46/5846057e28022268153beff6d352b06c.jpg
Title = The Black Maria
Rating = One Star(s)
Price = £52.15

推荐阅读