【发布时间】: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