简体   繁体   中英

How to get the contents inside of a div tag

I was wondering what I need to put inside of the .find parameter when using beautifulsoup to get the contents of "the-target" shown below.

<div class="item" the-target="this text" another-target="not this text"> 

This is the .find beautifulsoup parameter I am talking about

help = soup.find('div', 'What should I put here?').get_text()

Thanks

You can filter the div with class item and get the value of the-target key from the resulting tag object (which is a dict -like object):

soup.find('div', attrs={'class': 'item'})['the-target']

If you want to find by the the-target attribute:

soup.find('div', attrs={'the-target': 'this text'})

And get the value of the attribute like before:

soup.find('div', attrs={'the-target': 'this text'})['the-target']

In two steps:

tag = soup.find('div', attrs={'the-target': 'this text'})
the_target = tag.get('the-target')

You can use css selector to find item.

soup.select_one('div.item')['the-target']

OR

soup.select_one('.item')['the-target']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM