1

Here is the web CSS from which I want to extract the Location information.

<div class="location">
    <div class="listing-location">Location</div>
    <div class="location-areas">
    <span class="location">Al Bayan</span>
    ‪,‪
    <span class="location">Nepal</span>
    </div>
    <div class="area-description"> 3.3 km from Mall of the Emirates </div>
    </div>

Python Beautuifulsoup4 Code I used is:

   try:
            title= soup.find('span',{'id':'listing-title-wrap'})
            title_result= str(title.get_text().strip())
            print "Title: ",title_result
    except StandardError as e:
            title_result="Error was {0}".format(e)
            print title_result

Output:

"Al Bayanأ¢â‚¬آھ,أ¢â‚¬آھ

                            Nepal"

How can I convert the format into the following

['Al Bayan', 'Nepal']

What should be the line second of the code to get this output

WannaBeCoder
  • 1,280
  • 2
  • 17
  • 40
Panetta
  • 79
  • 1
  • 2
  • 8

3 Answers3

1

You're reading it wrong, just the read the spans with class location

soup = BeautifulSoup(html, "html.parser")
locList = [loc.text for loc in soup.find_all("span", {"class" : "location"})]
print(locList)

This prints exactly what you wanted:

['Al Bayan', 'Nepal']
Keatinge
  • 4,330
  • 6
  • 25
  • 44
  • [u'Al Bayan', 'u'Nepal] This is the output. – Panetta Jun 01 '16 at 07:22
  • map with string. That will give your expected result. `map(str,output_list)` – Rahul K P Jun 01 '16 at 07:24
  • @Panetta I've changed it slightly, run it now. There's no reason to use a map when there's already a list comp anyway – Keatinge Jun 01 '16 at 07:25
  • @Keatinge You are right. I just suggested an alternative option. – Rahul K P Jun 01 '16 at 07:26
  • @Panetta: do not call `str()` on Unicode strings—it breaks as soon as you get a non-ascii character in it. Format the list manually if you don't like: `[u'Al Bayan', 'u'Nepal] ` text representation e.g., `print("\n".join(locList))` (to print each item on its own line). See [Python string prints as [u'String'\]](http://stackoverflow.com/a/36891685/4279) – jfs Jun 01 '16 at 12:39
0

There is a one line solution. Consider a as your string.

In [38]: [i.replace("  ","") for i in filter(None,(a.decode('unicode_escape').encode('ascii','ignore')).split('\n'))]
Out[38]: ['Al Bayan,', 'Nepal']
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

You can use regexp to filter only letter and spaces :

>>> import re
>>> re.findall('[A-Za-z ]+', area_result)
['Al Bayan', ' Nepal']

Hope it'll be helpful.

3kt
  • 2,543
  • 1
  • 17
  • 29