Beautiful soup getting the first child

前端 未结 3 1861
深忆病人
深忆病人 2021-01-17 09:31

How can I get the first child?

 
London
York
3条回答
  •  无人及你
    2021-01-17 09:56

    With modern versions of bs4 (certainly bs4 4.7.1+) you have access to :first-child css pseudo selector. Nice and descriptive. Use soup.select_one if you only want to return the first match i.e. soup.select_one('.cities div:first-child').text. It is considered good practice to test is not None before using .text accessor.

    from bs4 import BeautifulSoup as bs
    
    html = '''
    
    London
    York
    ''' soup = bs(html, 'lxml') #or 'html.parser' first_children = [i.text for i in soup.select('.cities div:first-child')] print(first_children)

提交回复
热议问题