Beautiful Soup BS4标签导航

时间:2019-04-29 18:39:33

标签: python beautifulsoup

我正在尝试浏览此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 {}。不知道我是否做对了。提前谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

采用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?')]

答案 1 :(得分:0)

尝试一下:

print(t.contents)

t.attrs返回该标签属性的字典。

t.contents返回标签的内容(在开始和结束标签之间的内容)。

答案 2 :(得分:0)

根据我上面的评论,<p>标签没有属性。标签中显示的内容不在标签<p>…</p>之外。属性将位于标记内,例如:<p class="class_name" color="red">…</p>。要获取标签内的信息,请使用:

t = soup.p.string

更新:与您已经开始的工作保持一致,您可以使用json模块来获取“字典样式” 输出,如下所示:

import json
t_dict = json.loads(t)
t_dict  # this will output the json format data

希望这会有所帮助。