then it should give me a way to access the nested tags via the name or id of the HTML tag so that I can basically ask it to get me the content/text in the div tag with class='container' contained within the body tag, or something similar.
If you’ve used Firefox’s “Inspect element” feature (view HTML) you would know that it gives you all the tags in a nice nested manner like a tree.
I’d prefer a built-in module but that might be asking a little too much.
I went through a lot of questions on Stack Overflow and a few blogs on the internet and most of them suggest BeautifulSoup or lxml or HTMLParser but few of these detail the functionality and simply end as a debate over which one is faster/more efficent.
try:fromBeautifulSoupimportBeautifulSoupexceptImportError:from bs4 importBeautifulSoup
html =#the HTML code you've written above
parsed_html =BeautifulSoup(html)print(parsed_html.body.find('div', attrs={'class':'container'}).text)
So that I can ask it to get me the content/text in the div tag with class=’container’ contained within the body tag, Or something similar.
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
html = #the HTML code you've written above
parsed_html = BeautifulSoup(html)
print(parsed_html.body.find('div', attrs={'class':'container'}).text)
You don’t need performance descriptions I guess – just read how BeautifulSoup works. Look at its official documentation.
Here you can read more about different HTML parsers in Python and their performance. Even though the article is a bit dated it still gives you a good overview.
from lxml.html import parse
doc = parse('http://www.google.com').getroot()for div in doc.cssselect('a'):print'%s: %s'%(div.text_content(), div.get('href'))
And with cssselect it’s quite easy to use for scraping HTML pages too:
from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
print '%s: %s' % (div.text_content(), div.get('href'))
In my experience Beautiful Soup messes up on some complex HTML. I believe that is because Beautiful Soup is not a parser, rather a very good string analyzer.