【问题标题】:Parsing HTML contained in API call response解析 API 调用响应中包含的 HTML
【发布时间】:2020-07-04 16:27:33
【问题描述】:

我在弄清楚如何解析包含在 Python 3.7(请求 + BS4)中的 API 调用响应中的 HTML 时遇到了一些麻烦。

假设我想从 response like this one 中解析出文章 URL。

我能够获得响应的“渲染”条目,该条目似乎包含我要解析的 HTML,但是,当我将文本传递给 Beautiful Soup 的 HTML 解析器时,它似乎不起作用预期(无法找到任何类型的 HTML 标记):

import requests
from bs4 import BeautifulSoup

url = """https://www.washingtonpost.com/pb/api/v2/render/feature/?service=prism-query&contentConfig={%22url%22:%22prism://prism.query/ap-articles-by-site-id,/world%22,%22offset%22:0,%22limit%22:5}&customFields={%22isLoadMore%22:false,%22offset%22:0,%22maxToShow%22:50,%22dedup%22:true}&id=f00boImX29Vv3s&rid=&uri=/world/"""

r = requests.get(url).json()

soup = BeautifulSoup(r['rendering'], 'html.parser')

links_html = soup.find_all("div", attrs={"class":"headline x-small normal-style text-align-inherit "})
links = []
for div in links_html:
    links.append(div.find('a', href = True)['href'])

我认为响应中的“渲染”条目是原始 HTML 是不是错了?

【问题讨论】:

  • 请分享您的代码。还要确保已安装 lxml 并尝试使用 lxml 解析器。
  • 如果你检查我的回答,你会看到漂亮的汤 api 正在工作并且它正在 html 上执行,但你的 find_all 创新可能有问题

标签: python api parsing beautifulsoup python-requests


【解决方案1】:

您想使用json 库(或事后看来,Request.json()),因为您访问的任何链接实际上都不是网站,而是在它上面提供给您的 api html 以及编码、内容类型和其他一些不必要的东西。

我是这样做的。

>>> import requests
>>> from bs4 import BeautifulSoup
>>> r = requests.get("https://www.washingtonpost.com/pb/api/v2/render/feature/?service=prism-query&contentConfig=%7B%22url%22:%22prism://prism.query/ap-articles-by-site-id,/world%22,%22offset%22:0,%22limit%22:5%7D&customFields=%7B%22isLoadMore%22:false,%22offset%22:0,%22maxToShow%22:50,%22dedup%22:true%7D&id=f00boImX29Vv3s&rid=&uri=/world/")
>>> bs = BeautifulSoup(r.content, 'html.parser')
>>> first_div = bs.find("div", class_="moat-trackable")
>>> first_div
>>> import json
>>> html_dict = json.loads(r.content)
>>> html_dict
{'rendering': '<div class="moat-trackable ...'}
>>> html_dict.keys()
dict_keys(['rendering', 'encoding', 'contentType', 'pageResources', 'externalResources', 'httpHeaders'])
>>> bs = BeautifulSoup(html_dict["rendering"], 'html.parser')
>>> first_div = bs.find("div", class_="moat-trackable")
>>> first_div
<div class="moat-trackable 

【讨论】:

  • 摆弄你的例子让我遇到了我的实现问题。完全匹配我感兴趣的 div 的类不起作用(似乎是由于 HTML 中的转义字符反冲?)。近似匹配类名就可以了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 2018-12-21
  • 2016-05-28
  • 2021-08-04
  • 2021-04-27
  • 2019-02-08
  • 1970-01-01
相关资源
最近更新 更多