1

I am new to Python and BeautifulSoup. So please forgive me if I'm using the wrong terminology.

I am trying to get a specific 'text' from a div tag/element that has multiple attributes in the same .

<div class="property-item" data-id="183" data-name="Brittany Apartments" data-street_number="240" data-street_name="Brittany Drive" data-city="Ottawa" data-province="Ontario" data-postal="K1K 0R7" data-country="Canada" data-phone="613-688-2222" data-path="/apartments-for-rent/brittany-apartments-240-brittany-drive-ottawa/" data-type="High-rise-apartment" data-latitude="45.4461070" data-longitude="-75.6465360" >

Below is my code to loop through and find 'property-item'

for btnMoreDetails in citySoup.findAll(attrs= {"class":"property-item"}):

My question is, if I specifically want the 'data-name' and 'data-path' for example, how do I go about getting it?

I've searched google and even this website. Some were saying using the .contents[2]. But I still wasn't able to get any of it.

2 Answers 2

4

Once you have extracted the element (which findAll does one at a time) you can access attributes as though they were dictionary keys. So for example the following code:

data = """<div class="property-item" data-id="183" data-name="Brittany Apartments" data-street_number="240" data-street_name="Brittany Drive" data-city="Ottawa" data-province="Ontario" data-postal="K1K 0R7" data-country="Canada" data-phone="613-688-2222" data-path="/apartments-for-rent/brittany-apartments-240-brittany-drive-ottawa/" data-type="High-rise-apartment" data-latitude="45.4461070" data-longitude="-75.6465360" >"""

import bs4
soup = bs4.BeautifulSoup(data)
for btnMoreDetails in soup.findAll(attrs= {"class":"property-item"}):
    print btnMoreDetails["data-name"]

prints out

Brittany Apartments
1
  • Thank you! Solved and reps up to you
    – David.L
    Commented Jul 4, 2016 at 16:37
2

If you want to get the data-name and data-path attributes, you can simply use the dictionary-like access to Tag's attributes:

for btnMoreDetails in citySoup.findAll(attrs={"class":"property-item"}):
    print(btnMoreDetails["data-name"])
    print(btnMoreDetails["data-path"])

Note that you can also use the CSS selector to match the property items:

for property_item in citySoup.select(".property-item"):
    print(property_item["data-name"])
    print(property_item["data-path"])

FYI, if you want to see all the attributes use .attrs property:

for property_item in citySoup.select(".property-item"):
    print(property_item.attrs)
1
  • Thank you! Solved and reps up to you.
    – David.L
    Commented Jul 4, 2016 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.