Beautiful Soup [Python] and the extracting of text in a table

前端 未结 3 2081
不思量自难忘°
不思量自难忘° 2021-02-14 12:33

i am new to Python and to Beatiful Soup also! I heard about BS. It is told to be a great tool to parse and extract content. So here i am...:

I want to take the content

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 13:20

    First find the table (as you are doing). Using find rather than findall returns the first item in the list (rather than returning a list of all finds - in which case we'd have to add an extra [0] to take the first element of the list):

    table = soup.find('table' ,attrs={'class':'bp_ergebnis_tab_info'})
    

    Then use find again to find the first td:

    first_td = table.find('td')
    

    Then use renderContents() to extract the textual contents:

    text = first_td.renderContents()
    

    ... and the job is done (though you may also want to use strip() to remove leading and trailing spaces:

    trimmed_text = text.strip()
    

    This should give:

    >>> print trimmed_text
    This is a sample text
    >>>
    

    as desired.

提交回复
热议问题