使用BeautifulSoup将主表与子表刮除

2024-09-26 22:11:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试刮除一个似乎有嵌套子表的表。我最初试图编写一个循环,进一步深入到子表中,但我在解析它时遇到了困难。该网站是https://www.brilliantearth.com/design-your-own-engagement-ring/?nav=1,我正在尝试使用Python中的BeautifulSoup获取表的元素以存储到Pandas数据帧中。表中的每一行都有一个名为“inner item”的标记

似乎有一个单独的列标题表和另一个列出所有价格的表。如何解析要放入列表中的单元格元素?

import requests

import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'https://www.brilliantearth.com/design-your-own-engagement-ring/?nav=1'

soup = BeautifulSoup(response.content, 'html.parser')

# Find tables
all_tables=soup.find_all('table')
all_tables

# Select table with content we want
right_table = all_tables[-1]
right_table

# Generate lists
COMPARE=[]
SHAPE=[]
CARAT=[]
COLOR=[]
CLARITY=[]
CUT=[]
ORIGIN=[]
PRICE=[]

# Add elements from cells to corresponding list
for row in right_table.findAll("tr"):
    cells = row.findAll('td')

    COMPARE.append(cells[0])
    SHAPE.append(cells[0])
    CARAT.append(cells[0])
    COLOR.append(cells[0])
    CLARITY.append(cells[0])
    CUT.append(cells[0])
    ORIGIN.append(cells[0])
    PRICE.append(cells[0])

Tags: httpsimportrightcomtablesyourwwwtable

热门问题