Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the content of a Html page in Python

I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.

To be clear:

Input:

<html><head><title>Page title</title></head>
       <body><p id="firstpara" align="center">This is paragraph <b>one</b>.
       <p id="secondpara" align="blah">This is paragraph <b>two</b>.
       </html>

Output:

Page title This is paragraph one. This is paragraph two.

putting together:

from BeautifulSoup import BeautifulSoup
import re

def removeHtmlTags(page):
    p = re.compile(r'''<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>''')
    return p.sub('', page)

def removeHtmlTags2(page):
    soup = BeautifulSoup(page)
    return ''.join(soup.findAll(text=True))

Related

  • Python HTML removal
  • Extracting text from HTML file using Python
  • What is a light python library that can eliminate HTML tags? (and only text)
  • Remove HTML tags in AppEngine Python Env (equivalent to Ruby’s Sanitize)
  • RegEx match open tags except XHTML self-contained tags (famous don't use regex to parse html rant)
like image 696
Yin Zhu Avatar asked Dec 01 '22 06:12

Yin Zhu


1 Answers

Parse the HTML with Beautiful Soup.

To get all the text, without the tags, try:

''.join(soup.findAll(text=True))
like image 199
Oddthinking Avatar answered Dec 04 '22 07:12

Oddthinking