【问题标题】:Python requests double of everythingPython 请求所有内容的两倍
【发布时间】:2021-09-10 09:24:11
【问题描述】:

所以我正在尝试制作一个程序来获取 Spotify 个人资料图片。我可以获取图片的 URL,但问题是每个 URL 都有 2 个。

import requests
from bs4 import BeautifulSoup


list = ["https://open.spotify.com/user/0n7zzdkxmt0ldpo1kqugwca67",
        "https://open.spotify.com/user/1l23d3k5yq2v9ey191zp8uqxr",
]

for i in list:
    response = requests.get(i)

    html_content = response.content

    soup = BeautifulSoup(html_content, "html.parser")
    for i in soup.find_all("div",{"class":"bg lazy-image"}):
        print(i.get("data-src"))

结果如下:

https://i.scdn.co/image/ab6775700000ee85202880a205b627a7e6f25659
https://i.scdn.co/image/ab6775700000ee85202880a205b627a7e6f25659
https://i.scdn.co/image/ab6775700000ee85da40dde3363ed185d5e48a0a
https://i.scdn.co/image/ab6775700000ee85da40dde3363ed185d5e48a0a

Process finished with exit code 0

我的问题是,如果它们相同,我如何只打印其中一个?

【问题讨论】:

  • 你不应该使用list作为变量名

标签: python beautifulsoup python-requests


【解决方案1】:

在这种情况下,您只需将 iterable 转换为 set

    for i in set(soup.find_all("div",{"class":"bg lazy-image"})):
       print(i.get("data-src"))

通过这样做,可迭代对象内的所有重复项都将被根除

我强烈建议您阅读 Python 的数据结构

https://docs.python.org/3/tutorial/datastructures.html

【讨论】:

  • 您将 div 存储到一个集合中,同时删除重复的 urls 是预期的。
  • @bereal Ehm 我刚刚运行了您的代码,结果与给定的输入相同
  • 这是因为除了data-src 属性之外,div happen 是相同的。如果在某个时候它们有一些独特的属性,比如id,结果会有所不同。
  • 谢谢你们,我已经修复了代码,现在我将研究学习集。
【解决方案2】:

我会将它们转换为一组以删除重复项:

divs = soup.find_all("div",{"class":"bg lazy-image"})
urls = set(d.get('data-src') for d in divs) 

【讨论】:

    【解决方案3】:

    一个简单的解决方案就是检查 URL 是否等于最后一个 URL。

    import requests
    from bs4 import BeautifulSoup
    
    
    list = ["https://open.spotify.com/user/0n7zzdkxmt0ldpo1kqugwca67",
            "https://open.spotify.com/user/1l23d3k5yq2v9ey191zp8uqxr",
    ]
    
    for i in list:
        response = requests.get(i)
        html_content = response.content
    
        url = None
        soup = BeautifulSoup(html_content, "html.parser")
        for i in soup.find_all("div",{"class":"bg lazy-image"}):
            if i.get("data-src") != url:
                url = i.get("data-src")
                print(url)
    

    【讨论】:

    • 如果有3个url并且第一个和最后一个相同怎么办?
    • 这是基于页面中 url 顺序的假设。
    • 这里至少有几个假设,但它适用于提供的示例数据。但是@bereal 解决方案更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多