Reputation: 1079
I am trying to navigate the output from this API to get to a tag in the response. But after trying to navigate to the tag using standard method I get an empty response.
from bs4 import BeautifulSoup
import urllib.request
import gzip
import io
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.5',
}
url = 'https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&q=' + 'AKIAJQVBDUUDGLXOEKYA' + '&site=stackoverflow'
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
time.sleep(3)
if response.info().get('Content-Encoding') == 'gzip':
pagedata = gzip.decompress(response.read())
elif response.info().get('Content-Encoding') == 'deflate':
pagedata = response.read()
elif response.info().get('Content-Encoding'):
print('Encoding type unknown')
else:
pagedata = response.read()
soup = BeautifulSoup(pagedata, "lxml")
print(soup)
Output from soup:
<html><body><p>{"items":[{"tags":["c#","aws-lambda","aws-serverless"],"owner":{"reputation":188,"user_id":1395211,"user_type":"registered","accept_rate":62,"profile_image":"https://i.sstatic.net/WylN7.png?s=128&g=1","display_name":"Mostafa Fallah","link":"https://stackoverflow.com/users/1395211/mostafa-fallah"},"is_answered":true,"view_count":40,"accepted_answer_id":54550236,"answer_count":1,"score":2,"last_activity_date":1549445444,"creation_date":1540222981,"question_id":52933098,"link":"https://stackoverflow.com/questions/52933098/deploying-aws-serverless-lambda-application-with-amazonserverlessapplicationrepo","title":"Deploying AWS Serverless lambda Application with AmazonServerlessApplicationRepositoryClient does not work?"}],"has_more":false,"quota_max":300,"quota_remaining":275}</p></body></html>
This is what I used to navigate:
tags = soup.find_all('p')
t = tags[0]
print(type(t))
print(t.attrs)
But this returns and empty dict {} even though I can see things in the tag. Not sure if I am doing it right. Thank you for your help in advance.
Upvotes: 0
Views: 615
Reputation: 945
As per my comment above, there are no attributes for the <p>
tag. what you're seeing as tags are outside the tag: <p>…</p>
. attributes will be inside the tag, like so: <p class="class_name" color="red">…</p>
. To get to the information within the tags use:
t = soup.p.string
UPDATE: keeping in line with what you've already started, you could use json module to get the "dictionary-style" output as follows:
import json
t_dict = json.loads(t)
t_dict # this will output the json format data
Hope this helps.
Upvotes: 0
Reputation: 33384
The items in json format so you can do a json dump and and looping the items.
import requests
url = 'https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&q=' + 'AKIAJQVBDUUDGLXOEKYA' + '&site=stackoverflow'
s=requests.get(url).json()
data = [(item['tags'],item['owner'],item['title']) for item in s['items']]
print(data)
Output:
[([python', beautifulsoup'], {user_id': 7309225, profile_image': https://graph.facebook.com/10207802462833592/picture?type=large', user_type': registered', reputation': 532, link': https://stackoverflow.com/users/7309225/digvijay-sawant', accept_rate': 100, display_name': Digvijay Sawant'}, Beautiful Soup BS4 tag navigation'), ([c#', aws-lambda', aws-serverless'], {user_id': 1395211, profile_image': https://i.sstatic.net/WylN7.png?s=128&g=1', user_type': registered', reputation': 188, link': https://stackoverflow.com/users/1395211/mostafa-fallah', accept_rate': 62, display_name': Mostafa Fallah'}, Deploying AWS Serverless lambda Application with AmazonServerlessApplicationRepositoryClient does not work?')]
Upvotes: 1
Reputation: 2694
Try this:
print(t.contents)
t.attrs returns a dictionary of attributes of that tag.
t.contents returns the content (the thing between opening and closing tag) of a tag.
Upvotes: 0