BeautifulSoup 忽略 table 中嵌套的 table

BeautifulSoup ignore nested tables inside table

与 BeautifulSoup 一起为 Python 解析网页(不幸的是,这主要是在 table 中编写的)。

这是我正在尝试使用的内容的摘录

<tr>
  <td colspan="4">
    <div class="shortmenucats">
        <span style="color: ">
            -- Fresh Baked Pastries --

        </span>
    </div>
  </td>
</tr>
<tr>  
  <td width="80%" valign="top">
    <table width="100%" cellspacing="0" cellpadding="0" border="0">
        <tbody>
            <tr>
                <td>
                    <div class="shortmenurecipes">
                        <span style="color: #000000"> Chocolate Doughnut Holes </span>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
  </td>
  <td width="5%" valign="top"></td>
  <td width="10%" valign="top" align="right" colspan="1">
    <div class="shortmenuprices">
        <span style="color: #000000"></span>
    </div>
  </td>
  <td width="5%" valign="top" colspan="1">
  </td>
</tr>

这些是 table 中的两行,其中有 10 行,它们像那样交替(div in td,table in td,div in td , table 在 td 等).

我正在使用 BeautifulSoup 在父 table 上调用 find_all 并且由于嵌套 table.

我首先做了一个 table.find_all('td', recursive=False),但根本没有 return 任何一个。 如果我在父 table 上调用 findChildren(),我会得到一个包含一个结果的列表,但结果中包含所有子项。

我是不是做错了什么?我不知道如何解决这个问题。

如果你想要我正在解析的实际网站,请看这里: http://138.23.12.141/foodpro/shortmenu.asp?sName=University+of+California%2C+Riverside+Dining+Services&locationNum=02&locationName=Lothian+Residential+Restaurant&naFlag=1

编码很乱。我只是想解析它。

如有任何帮助,我们将不胜感激。即使它只是一种删除重复项的方法。

谢谢。

您可以通过 HTML 中的深度来识别您的目标表。

下面是一些代码,这些代码将 select 那些嵌套在深度 3 的表:

tables = soup.findAll("table")
depth3 = []
for t in tables:
  if len(t.find_parents("table")) == 3:
    depth3.append(t)

对于您的页面,这会产生 6 个表格 selected - 三个用于 headers("Breakfast"、"Lunch"、"Dinner")和三个对于菜单。它们交替 - header、菜单、header、菜单等,因此您可以只处理位置 1、3 和 5 的表格。

你的解析现在应该容易多了。

这里的另一种选择是依赖菜单的 class 名称和里面的类别,并且仅在下到元素的直接父级时才使用 recursive=False

完整的工作代码 提取菜单:

from urllib2 import urlopen
from bs4 import BeautifulSoup

url = "http://138.23.12.141/foodpro/shortmenu.asp?sName=University+of+California%2C+Riverside+Dining+Services&locationNum=02&locationName=Lothian+Residential+Restaurant&naFlag=1"
soup = BeautifulSoup(urlopen(url))

container = soup.find('div', class_='shortmenutitle').find_next_sibling('table').tr
for td in container.find_all('td', recursive=False):
    title = td.find('div', class_='shortmenumeals')

    print title.text.strip()
    for item in td.table.find_all('tr', recursive=False)[1].table.find_all('tr', recursive=False):
        print item.text.strip()
    print "-----"
    print

打印完整菜单(无重复):

Breakfast
-- Fresh Baked Pastries --
Chocolate Doughnut Holes
Double Chocolate Mini Muffin
Fresh Baked Blueberry Bagel
Fresh Baked Plain Bagel
-- Breakfast Parfait Bar --
(V,GF) Breakfast Parfait Bar
-- Hot Cereal & Toppings --
(V) Cream of Wheat
-- Breakfast Offerings --
(V) Belgium Waffle Bar with Condiments
(V) Eggs Rancheros
(V) Vanilla Scented French Toast
(V)Hash Browns
(V.GF) Scrambled Eggs
Corned Beef Hash
Turkey Sausage Patty
-- Omelet Bar --
(V,GF) Omelet Bar (Egg Whites Available Upon Request)
-----

Lunch
-- Soup & Deli Bar --
(V) Broccoli Cheese
Artisian Bread Bar
Chicken Tortilla
N Y Style Deli Bar
-- Global Sizzle --
(V) Jasmine Rice
(V) Steamed Sugar Snap Peas
(V) Thai Vegetable Spring Roll
Red Thai Curry Chicken (contains peanuts)
Sweet Thai Chili & Plum Dipping Sauces
Thai Curry Shrimp w/ Green Pepper
-- Urban Kitchen --
(V) Peruvian Beans
Peruvian Rotissere Chicken
-- The Grill --
(GF) Marinated Grilled Chicken Breast
(V) Skinny Fries
Turkey Club Melt
-- Healthy Vegetarian Bar --
(V) Southwestern Corn Salad
Southwest Soy Beef Wrap
-- Desserts --
Bakery Parfait Bar
Chocolate 1/2 Sheet Cake
Chocolate Mousse
Sugar Free Strawberry Orange Jell-O Gems
-- Continous Service 2pm-4:30pm --
(V) Vietnamese Tofu Spring Roll w/Sauces
Rotini w/Chicken Tomato Cream Spinach
Rotini w/Tomato Cream Spinach
Vietnamese Spring Roll with Tofu
-----

Dinner
-- Soup & Deli Bar --
(V) Broccoli Cheese
Artisian Bread Bar
Chicken Tortilla
N Y Style Deli Bar
-- Spinellis Pizza --
(V)French Bread Three Cheese Pizza
French Bread Pepperoni Pizza
-- Global Sizzle --
Beef Pho Bo Bar
Vegetable Pho Chay Bar
-- Urban Kitchen --
Mashed Sweet Potatoes
Rotissere Porkloin w/Apricot Demi Glace
-- The Grill --
(GF) Marinated Grilled Chicken Breast
(V) Seasoned Wedge Fries
Chicken Tenders
-- Healthy Vegetarian Bar --
(V) Cut Corn
(V) Steamed Broccoli
(Vgn) Black Bean Tostadas
-- Desserts --
Bakery Parfait Bar
Chocolate 1/2 Sheet Cake
Chocolate Mousse
M & M Rice Krispy Treats
Oreo Cheesecake
Peach Maple Cobbler
Sugar Free Strawberry Orange Jell-O Gems
-----