首页 > 解决方案 > 用美丽的汤循环麻烦

问题描述

我是 python 的新手,目前正在学习使用BeautifulSoup. 我正在尝试获取有关 Steam 的信息以显示游戏名称、价格和类型。我可以让我的代码找到所有这些,但是当我放入 for 循环时,它不起作用。你能找出问题所在吗?

非常感谢你的帮助!

这将在页面上显示我需要(以及更多)的所有内容(名称、价格、类型) *

from bs4 import BeautifulSoup
import requests
import json
url = 'https://store.steampowered.com/tags/en/Adventure/#p=0&tab=NewReleases'
response = requests.get(url, timeout=9)
content = BeautifulSoup(response.content, "html.parser")
for item in content.findAll("div", attrs={"id": "tab_content_NewReleases"}):
    print(item.text)

这只会显示第一场比赛,因此我认为它没有正确循环*

from bs4 import BeautifulSoup
import requests
import json
url = 'https://store.steampowered.com/tags/en/Adventure/#p=0&tab=NewReleases'
response = requests.get(url, timeout=9)
content = BeautifulSoup(response.content, "html.parser")
for item in content.findAll("div", attrs={"id": "tab_content_NewReleases"}):
    itemObject = {
        "name": item.find("div", attrs={"class": "tab_item_name"}).text,
        "price": item.find("div", attrs={"class": "discount_final_price"}).text,
        "genre": item.find("div", attrs={"class": "tab_item_top_tags"}).text
    }
    print(itemObject)

我期待这样的结果,但超过 1 个结果:

{
    'name': 'Little Misfortune', 
    'price': '$19.99', 
    'genre': 'Adventure, Indie, Casual, Singleplayer'
}

标签: pythonweb-scrapingbeautifulsoup

解决方案


我认为您没有选择正确的标签。改为使用“NewReleasesRows”来查找包含新版本行的表。所以使用 CSS 选择器的代码会是这样的:

my_soup: BeautifulSoup = BeautifulSoup(my_page_text, 'lxml')
print("mysoup type:", type(my_soup))

my_table_list = my_soup.select('#NewReleasesRows')
print('my_table_list size:', len(my_table_list))

然后您可以查找行(在检查您只有一个表之后(也可以使用 select_one):

print(BeautifulSoup.prettify(my_table_list[0]))
my_table_rows = my_table_list[0].select('.tab_item')

从那里你可以迭代

for my_row in my_table_rows:
    print(my_row.get_text(strip=True))

结果代码:R 130.00Little MisfortuneAdventure, Indie, Casual, Singleplayer -33%R 150.00R 100.50TrailmakersBuilding, Sandbox, Multiplayer, LEGO -10%R 105.00R 94.50Devil's Deck 秘境恶魔境抢先体验, RPG, Indie, Early Access R 89.00Showdown强盗动作, 冒险, 独立, 恐怖 R 150.00HardlandAdventure, 独立, 开放世界, 单人 R 120.00Aeon's EndCard Game, 策略, 独立, Adventure R 105.00Atomorf2休闲, 动作, 独立, 冒险 -10%R 175.00R 157.50Daymare: 1998独立, 动作,生存恐怖, 恐怖 -25%R 79.00R 59.25Ling: A Road Alone动作, 角色扮演, 独立, 血腥 -10%R 105.00R 94.50Nauticrawl独立, 模拟, 氛围, 科幻 FreeOrpheus's Dream免费游戏, 冒险, 独立, 休闲 -40 %R 105.00R 63.00AVA 抢先体验、动作、抢先体验、独立 -40%R 18.00R 10.80Angry Golf 独立、休闲、体育、冒险 -40%R 10.00R 6.00Death Live独​​立, 休闲, 冒险, 动漫 -30%R 130.00R 91.00Die Young 生存, 动作, 开放世界, 血腥

我希望这会有所帮助。最好的


推荐阅读