使用 Python BrickEconomy 网站进行数据抓取

问题描述 投票:0回答:1

我正在使用我编写的代码从网站“https://www.brickeconomy.com/sets/year/2024”抓取数据。我设法从表中提取乐高套装的名称,但无法访问其余数据,例如“年份”、“主题/子主题”、“件/小人仔”、“可用性”、“零售”和“价值” ”。我想详细访问每个项目中的数据并将其保存为 JSON 格式。如果可能的话,我还想附上乐高套装的图片链接。下面是我的代码示例。

from bs4 import BeautifulSoup
import cloudscraper
import json

url = "https://www.brickeconomy.com/sets/year/2024"

scraper = cloudscraper.create_scraper()
response = scraper.get(url)

if response.status_code == 200:
    soup = BeautifulSoup(response.content, 'html.parser')
    print(soup.prettify())

    sets_data = []

    table_rows = soup.find('table', id='ContentPlaceHolder1_ctlSets_GridViewSets').find_all('tr', align='left')

    for row in table_rows:
        cells = row.find_all('td')
        if len(cells) >= 3:
            try:
                set_name = cells[2].find('div').get_text(strip=True)
            except AttributeError:
                set_name = "-"
            try:
                set_year = soup.find('div', string='Year').find_next_sibling().get_text(strip=True)
            except AttributeError:
                set_year = "-"

            print("set-id:", set_name)
            print("set-year:", set_year)
            print()

            set_info = {
                "set-id": set_name,
                "set-year": set_year
            }

            sets_data.append(set_info)

        with open('sets_data.json', 'w', encoding='utf-8') as json_file:
            json.dump(sets_data, json_file, ensure_ascii=False, indent=4)

    print("saved Json file")

else:
    print("HTTP Error Code:", response.status_code)
python python-3.x web-scraping beautifulsoup
1个回答
0
投票

问题似乎在于您如何尝试从表中提取数据。您要查找的数据不是直接在带有字符串“Year”的 div 下,而是在每行的 td 元素中。

© www.soinside.com 2019 - 2024. All rights reserved.