【问题标题】:Combining two loops into one in Python在 Python 中将两个循环合二为一
【发布时间】:2022-12-01 01:54:19
【问题描述】:

如何将这两个循环组合在一起?它们都是独立工作的,我怎么能把它们合二为一呢?

from bs4 import BeautifulSoup

with open("games.html", "r") as page:
    doc = BeautifulSoup(page, "html.parser")

titles = doc.select("a.title")
prices = doc.select("span.price-inner")

for game_soup in doc.find_all("div", {"class": "game-options-wrapper"}):
    game_ids = (game_soup.button.get("data-game-id"))

for title, price_official, price_lowest in zip(titles, prices[::2], prices[1::2]):
    print(title.text + ',' + str(price_official.text.replace('$', '').replace('~', '')) + ',' + str(
        price_lowest.text.replace('$', '').replace('~', '')))

输出:

110837
Call of Duty: Modern Warfare II (2022),69.99,77.05

我需要同一行中其他值旁边的值 预期输出:

Call of Duty: Modern Warfare II (2022),69.99,77.05,110837

【问题讨论】:

  • 遍历文档中的所有元素并使用“if..elif...”块来确定您是否应该更新game_idtitle。但是您可能不会以单个循环结束,而是以各种条件和嵌套循环结束。也许还有一些变量,具体取决于您要抓取的内容。
  • 我需要一起运行它们,而不是一个或另一个
  • 110837\nCall of Duty: Modern Warfare II (2022) 是来自一个标题吗?

标签: python loops web-scraping beautifulsoup


【解决方案1】:

我觉得所有 3 个细节(标题、price_official、price_lowest)可能都在一个共享容器中。最好遍历这些容器并从每个容器中选择详细信息作为集合,以确保价格和标题配对,但我不能告诉你如何做到这一点,除非至少看到一个 sn-p来自(或全部)“games.html”......


无论如何,假设 '110837 Call of Duty: Modern Warfare II (2022)' 来自这里的第一个标题,您可以将最后一个循环重写为:

for z in zip(titles, prices[::2], prices[1::2]):
    z, lw = list(z), ''
    for i in len(z):
        if i == 0: # title
            z[0] = ' '.join(w for w in z[0].text.split('
', 1)[-1] if w)
            if '
' in z[0].text: lw = z[0].text.split('
', 1)[0]
            continue
        z[i] = z[i].text.replace('$', '').replace('~', '')
    print(','.join(z+[lw]))

【讨论】:

    猜你喜欢
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多