首页 > 解决方案 > 美汤BS4标签导航

问题描述

我正在尝试导航此 API 的输出以获取响应中的标签。但是在尝试使用标准方法导航到标签后,我得到一个空响应。

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)

汤的输出:

<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.stack.imgur.com/WylN7.png?s=128&amp;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>

这是我用来导航的:

tags  = soup.find_all('p')
t = tags[0]
print(type(t))
print(t.attrs)

但是即使我可以在标签中看到东西,这也会返回并清空 dict {}。不确定我是否做得对。提前谢谢你的帮助。

标签: pythonbeautifulsoup

解决方案


json 格式的项目,因此您可以进行 json 转储和循环项目。

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)

输出:

[([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.stack.imgur.com/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?')]

推荐阅读