I’m developing a Python scraper at scraperwiki.com and I need to parse a html page that containt the following:
<div class="items">
<div class="item">
ItemLine1 ItemLine1 ItemLine1
<br>
ItemLine2 ItemLine2 ItemLine2
</div>
<br>
</div>
What I’m doing now is:
import scraperwiki
import lxml.html
#.......................
raw_string = lxml.html.fromstring(scraperwiki.scrape(url_to_scrape))
my_line = ((raw_string.cssselect("div.items div.item")[0]).text)
print (my_line)
and it prints ItemLine1 ItemLine1 ItemLine1 only. When I change [0] to [1] it throws an exception.
How do I scrape that? Should I use xpath?
XPath is the most straightforward solution:
The XPath
br[1]selects the firstbrchild ofdiv.item; Thepreceding-sibling::axis contains all nodes that occur before the firstbr;node()selects every kind of node (text or elements) that are in that axis.If your larger goal is to split up the children of a node by
brelements, you can take a few different approaches. The reason this is so tricky is that elements likebrandhrare badly designed markup. Using a tree-like markup language like sgml, html, or xml, things that should be together should be grouped by a common parent element rather than split by a childless delimiter element.I’ll expand your test case to demonstrate some more complex situations:
The first approach is to simply get all nodes in the paragraph and split them into different lists by
br. If you use this approach, don’t use thetextandtailattributes of the ElementTree API because you will probably end up duplicating text.This produces lists like so:
A second approach is to make use of the ElementTree API and keep text nodes in the
textandtailattributes. The downside of this approach is that if there is no element to attach the text, we need to just include the text node. This list of non-homogenous types is a bit more trouble to work with.This produces a list like so. Note that in contrast to the previous list it only has text nodes nodes in the first position of the list. This corresponds to the
br.tailtext orparent.text(which is text before the first element).I think the best approach is to introduce new elements. This html is using
brwhen it should be usingpor some other container element. So instead, let’s fix the html and return a list of elements instead of a list of list of nodes:This prints the following:
See how items are grouped by a new
paraelement, which doesn’t exist in the original document.