问题描述
response = requests.request("GET",url,headers=headers)
print(response.text)
pdfLinks = []
我用api提取了这样的结果,很长。这个response.text好像是字符串,不是字典。
{"results":[{"title":"montrac® INTELLIGENCE IN MOTION - montratec","link":"https://www.montratec.de/fileadmin/user_upload/footer/montratec_Design_Guide_ENG.pdf","description":"„With montratec's technology,we Could customize the transport system according to our production needs,eliminating dust,reducing consumption and optimizing. Missing: filetype= filetype=",.....},
对于列表中的每个项目,我只想提取其“链接”元素并将其放入新列表中。我怎样才能做到这一点?
解决方法
已更新以匹配您的问题更新。
您可以使用 data = response.json()
将信息直接返回到字典中,因为您使用的是请求模块。
如果您想继续作为字符串(不推荐)而不是字典,您可以在其上运行literal_eval(来自ast库)。
然后使用 dict.get 和 list comprehension 你可以得到你想要的。
.get 将返回键 'results' 的值,如果它不存在则返回 None 并且不抛出任何 KeyErrors。
列表推导式根据内部本质上是一个 for 循环的结果创建一个新列表,该循环遍历结果的内容。
with requests.request("GET",url,headers=headers) as resp:
data = resp.json()
foo = [i['link'] for i in data.get('results')]
如果你出于某种原因想把它保留为一个字符串
from ast import literal_eval
a = str({"results":[{"title":"montrac® INTELLIGENCE IN MOTION - montratec","link":"https://www.montratec.de/fileadmin/user_upload/footer/montratec_Design_Guide_ENG.pdf","description":"„With montratec's technology,we could customize the transport system according to our production needs,eliminating dust,reducing consumption and optimizing. Missing: filetype= filetype="}]})
b = literal_eval(a)
c = [i['link'] for i in b.get('results')]
print(c)
['https://www.montratec.de/fileadmin/user_upload/footer/montratec_Design_Guide_ENG.pdf']