Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8750173
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T12:49:16+00:00 2026-06-13T12:49:16+00:00

I’m developing a Python scraper at scraperwiki.com and I need to parse a html

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T12:49:17+00:00Added an answer on June 13, 2026 at 12:49 pm

    XPath is the most straightforward solution:

    items = raw_string.cssselect('div.items div.item')
    
    texts = [item.xpath('br[1]/preceding-sibling::node()') for item in items]
    

    The XPath br[1] selects the first br child of div.item; The preceding-sibling:: axis contains all nodes that occur before the first br; 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 br elements, you can take a few different approaches. The reason this is so tricky is that elements like br and hr are 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:

    html = """<div class="items">
      <div class="item">
       <br>
       ItemLine1 ItemLine1 ItemLine1
       <a href="">item</a>
       Itemline1-b
       <br> 
       <a class="z">item2</a>
       ItemLine2 ItemLine2 ItemLine2
       <br><br>
       Itemline3
     </div>
     <br>
    </div>"""
    
    doc = lxml.html.fromstring(html)
    itemlist = doc.cssselect('div.items div.item')
    

    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 the text and tail attributes of the ElementTree API because you will probably end up duplicating text.

    def paras_by_br_nodes(parent):
        """Return a list of node children of parent (including text nodes) grouped by "paragraphs" which are delimited by <br/> elements."""
        paralist = []
        paras = []
        for node in parent.xpath('node()'):
            if getattr(node, 'tag', None) == 'br':
                paralist.append(paras)
                paras = []
            else:
                paras.append(node)
            paralist.append(paras)
            return paralist
    
    
    print paras_by_br_nodes(itemlist[0])
    

    This produces lists like so:

    [['\n       '],
     ['\n       ItemLine1 ItemLine1 ItemLine1\n\t\t', <Element a at 0x10498a350>, '\n\t\tItemline1-b\n       '],
     [<Element a at 0x10498a230>, '\n       ItemLine2 ItemLine2 ItemLine2\n       '],
     [], 
     ['\n       Itemline3\n ']]
    

    A second approach is to make use of the ElementTree API and keep text nodes in the text and tail attributes. 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.

    def paras_by_br_text(parent):
        paralist=[]
        para=[parent.text]
        for item in parent:
            if item.tag=='br':
                paralist.append(para)
                para = [item.tail]
            else:
                para.append(item)
        paralist.append(para)
        return paralist
    
    print paras_by_br_text(itemlist[0])
    

    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.tail text or parent.text (which is text before the first element).

    [['\n       '],
     ['\n       ItemLine1 ItemLine1 ItemLine1\n\t\t', <Element a at 0x1042f5170>],
     [<Element a at 0x1042f5290>],
     [],
     ['\n       Itemline3\n ']]
    

    I think the best approach is to introduce new elements. This html is using br when it should be using p or 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:

    def paras_by_br(parent):
        paralist = []
        para = lxml.html.etree.Element('para')
        if parent.text:
            para.text = parent.text
        for item in parent:
            if item.tag=='br':
                paralist.append(para)
                para = lxml.html.etree.Element('para')
                if item.tail:
                    para.text = item.tail
            else:
                para.append(item)
        return paralist
    
    paralist = paras_by_br(itemlist[0])
    
    print "\n--------\n".join(lxml.html.etree.tostring(para) for para in paralist)
    

    This prints the following:

    <para>
           </para>
    --------
    <para>
           ItemLine1 ItemLine1 ItemLine1
            <a href="">item</a>
            Itemline1-b
           </para>
    --------
    <para><a class="z">item2</a>
           ItemLine2 ItemLine2 ItemLine2
           </para>
    --------
    <para/>
    

    See how items are grouped by a new para element, which doesn’t exist in the original document.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I need a function that will clean a strings' special characters. I do NOT
I have thousands of HTML files to process using Groovy/Java and I need to
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I have a small JavaScript validation script that validates inputs based on Regex. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.