41

I have am trying to parse a webpage that looks like this with Python->Beautiful Soup:enter image description here

I am trying to extract the contents of the highlighted td div. Currently I can get all the divs by

alltd = soup.findAll('td')

   
for td in alltd:
    print td

But I am trying to narrow the scope of that to search the tds in the class "tablebox" which still will probably return 30+ but is more managable a number than 300+.

How can I extract the contents of the highlighted td in picture above?

4

1 に答える 1

77

BeautifulSoup が 1 つの要素内で見つけた要素は、その親要素と同じ型であることを知っておくと便利です。つまり、さまざまなメソッドを呼び出すことができます。

したがって、これはあなたの例ではいくらか機能するコードです:

soup = BeautifulSoup(html)
divTag = soup.find_all("div", {"class": "tablebox"})

for tag in divTag:
    tdTags = tag.find_all("td", {"class": "align-right"})
    for tag in tdTags:
        print tag.text

これにより、「tablebox」クラスのtd親を持つ「align-right」クラスのすべてのタグのすべてのテキストが出力されます。div

于 2012-11-02T19:58:47.480 に答える