首页 > 解决方案 > 如何拍摄多张图片链接

问题描述

def get_links(statu, data, n_img, url, agent):
    if statu==0:
        print("The website doesn't response. Please try again later",end=" ")
    else:
        img_links=[]
        r=requests.get(url,headers=agent).text
        soup=BeautifulSoup(r,"lxml")
        results=soup.find_all("div",attrs={"class":"view"})
        results=soup.find_all("div",attrs={"class":"view"})
        results=soup.find_all("div",attrs={"class":"interaction-view"})
        results=soup.find_all("div",attrs={"class":"photo-list-photo-interaction"})
        # results=soup.find_all("a",attrs={"class":"overlay"},limit=n_img)
        print(results)
        for result in results:
            link=result.get("href")
            img_links.append(link)
        return img_links

为了下载多个图像,我尝试从Flickr获取链接。为此,我编写了上面的代码,一切都很好,直到出现“results=soup.find_all("div",attrs={"class":"photo-list-photo-interaction"})" 这一行。在该行之前,我可以使用 HTML 代码。但是,在那条线上我无法得到它。我该如何解决这个问题。谢谢!

标签: pythonbeautifulsouprequestpython-requestsurllib

解决方案


与其用 Beautiful Soup 刮,为什么不使用API呢?或者,您可以使用Flickr 的 RSS Feeds并使用 feedparser 模块解析它们。

如果您仍想使用 BeautifulSoup:

def flickr_photos(url):
    img_urls = []
    resp = requests.get(url)
    soup = BeautifulSoup(resp.text)

    photos = soup.find_all('div', {'class': 'view'})

    for photo in photos:
        try:
            img = photo['style'].split('(//').pop()
            if img.startswith('live'):
                img_urls.append(f'https://{img[:-1]}')
        except:
            pass
    return img_urls

您的代码不起作用的原因是因为 Flickr 在background-image样式属性中有图像的 url。


推荐阅读