Click here to Skip to main content
15,889,861 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to get the value "test" out of "data" by using Beautifulsoup. Is this possible with dictionary keys and values like below?
<div class="cell" data="test">


What I have tried:

Python
import requests
import bs4

result = requests.get("url")

if result.status_code == 200:
    soup = bs4.BeautifulSoup(result.text,"lxml")
    print(soup.find_all("div", {'class':'cell'}['data']))
Posted
Updated 5-Jan-22 23:55pm
Comments
Richard MacCutchan 5-Jan-22 8:29am    
What happens when you run the code?
Member 13554627 5-Jan-22 8:34am    
Error:
print(soup.find_all("div", {'class':'cell'}['data']))
KeyError: 'data'

then I will get a keyError.

1 solution

The find_all function returns a collection of objects, so you need to iterate the collection before you can use an index. Something like:
Python
divs = soup.find_all("div", {'class':'cell'})
for div in divs:
    print(div['data'])

Or, if you are certain that the first one in the list is the one you want then:
Python
print(soup.find_all("div", {'class':'cell'})[0]['data'])
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900