Skip to main content
 首页 » 编程设计

python之通过 Web Scraping Python 检索 Imgur 图像链接

2024年11月01日38lautakyan007

我正在尝试使用 imgur.com 检索图像的链接。图片(如果是 .jpg 或 .png)似乎通常存储在他们网站上的 (div class="image post-image") 中,例如:

<div class='image post-image'> 
    <img alt="" src="//i.imgur.com/QSGvOm3.jpg" original-title="" style="max-width: 100%; min-height: 666px;"> 
</div> 

到目前为止,这是我的代码:

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
 
url = 'https://imgur.com/gallery/0PTPt' 
html = urlopen(url) 
soup = BeautifulSoup(html, 'lxml') 
info = soup.find_all('div', {'class':'post-image'}) 
 
file = open('imgur-html.txt', 'w') 
file.write(str(info)) 
file.close() 

我的输出不是能够获取这些标签中的所有内容:

<div class="post-image" style="min-height: 666px"> 
</div>  

我需要做什么才能进一步访问它以获得图片链接?或者这只是我只需要使用 API 的地方?感谢您的帮助。

请您参考如下方法:

它会出现的子 img 是动态添加的,但不存在。您可以从 rel 中提取完整链接

import requests 
from bs4 import BeautifulSoup as bs 
 
r = requests.get('https://imgur.com/gallery/0PTPt') 
soup = bs(r.content, 'lxml') 
print(soup.select_one('[rel=image_src]')['href'])