Rushil Srivastava
Rushil Srivastava

Reputation: 297

Python: BeautifulSoup - Get an attribute value from the name of a class

I am scraping items from a webpage (there are multiple of these):

<a class="iusc" style="height:160px;width:233px" m="{&quot;cid&quot;:&quot;T0QMbGSZ&quot;,&quot;purl&quot;:&quot;http://www.tti.library.tcu.edu.tw/DERMATOLOGY/mm/mmsa04.htm&quot;,&quot;murl&quot;:&quot;http://www.tti.lcu.edu.tw/mm/img0035.jpg&quot;,&quot;turl&quot;:&quot;https://tse2.mm.bing.net/th?id=OIP.T0QMbGSZbOpkyXU4ms5SFwEsDI&amp;pid=15.1&quot;,&quot;md5&quot;:&quot;4f440c6c64996cea64c975389ace5217&quot;}" mad="{&quot;turl&quot;:&quot;https://tse3.mm.bing.net/th?id=OIP.T0QMbGSZbOpkyXU4ms5EsDI&amp;w=300&amp;h=200&amp;pid=1.1&quot;,&quot;maw&quot;:&quot;300&quot;,&quot;mah&quot;:&quot;200&quot;,&quot;mid&quot;:&quot;C303D7F4BB661CA67E2CED4DB11E9154A0DD330B&quot;}" href="/images/search?view=detailV2&amp;ccid=T0QMbGSZ&amp;id=C303D7F4BB661E2CED4DB11E9154A0DD330B&amp;thid=OIP.T0QMbGSZbOpkyXU4ms5SFwEsDI&amp;q=searchtearm;amp;simid=6080204499593&amp;selectedIndex=162" h="ID=images.5978_5,5125.1" data-focevt="1"><div class="img_cont hoff"><img class="mimg" style="color: rgb(169, 88, 34);" height="160" width="233" src="https://tse3.mm.bing.net/th?id=OIP.T0QMbGSZ4ms5SFwEsDI&amp;w=233&amp;h=160&amp;c=7&amp;qlt=90&amp;o=4&amp;dpr=2&amp;pid=1.7" alt="Image result fsdata-bm="169" /></div></a>

What I want to do is download the image and information associated with it in the m attribute.

To accomplish that, I tried something like this to get the attributes:

links = soup.find_all("a", class_="iusc")

And then, to get the m attribute, I tried something like this:

for a in soup.find_all("m"):
    test = a.text.replace("&quot;" '"')
    metadata = json.loads(test)["murl"]
    print(str(metadata))

However, that doesn't quite work as expected, and nothing is printed out (with no errors either).

Upvotes: 2

Views: 4744

Answers (1)

Himal
Himal

Reputation: 1371

You are not iterating through the links list. Try this.

links = soup.find_all("a", class_="iusc")

for link in links:
    print(link.get('m'))

Upvotes: 2

Related Questions