How to get a nested element in beautiful soup

前端 未结 2 1631
深忆病人
深忆病人 2020-12-05 10:31

I am struggling with the syntax required to grab some hrefs in a td. The table, tr and td elements dont have any class\'s or id\'s.

If I wanted to grab the anchor i

2条回答
  •  不知归路
    2020-12-05 10:54

    Something like this?

    from BeautifulSoup import BeautifulSoup
    soup = BeautifulSoup(html)
    anchors = [td.find('a') for td in soup.findAll('td')]
    

    That should find the first "a" inside each "td" in the html you provide. You can tweak td.find to be more specific or else use findAll if you have several links inside each td.

    UPDATE: re Daniele's comment, if you want to make sure you don't have any None's in the list, then you could modify the list comprehension thus:

    from BeautifulSoup import BeautifulSoup
    soup = BeautifulSoup(html)
    anchors = [a for a in (td.find('a') for td in soup.findAll('td')) if a]
    

    Which basically just adds a check to see if you have an actual element returned by td.find('a').

提交回复
热议问题