簡體   English   中英

如何使用 python 從網頁提要下載圖像

[英]How to download an image from a webpage feed with python

我對 python 有點陌生,我正在嘗試編寫一個腳本,從提要中獲取第一張圖片(這意味着這張圖片會每隔幾個小時發生變化,所以我不能只使用它的網址)並將其下載到一個指定的文件。 這是我到目前為止所寫的

import requests

res = requests.get('image_url')

with open('./folder/img.png', 'wb') as f:
    f.write(res.content)

print('Done!')

我不想像上面顯示的那樣直接放置圖像 url,而是讓它自動從網站獲取圖像。

我最終使用請求模塊來獲取 web 頁面,然后是 BeautifulSoup4 頁面來解析它,最后使用正則表達式來匹配任何帖子/圖像 url

import bs4, requests, re

res = requests.get('https://www.reddit.com/')
page = bs4.BeautifulSoup(res.text, 'html.parser')

mo = [img for img in page.find_all('img', {'alt': 'Post image'})]

urlReg = re.compile(r'https://preview.redd.it/\w+.jpg?\S+')
links = urlReg.findall(str(mo))

我仍然有一個問題,有時正則表達式與頁面中的任何 url 都不匹配,即使我很確定那里有不止一個,我必須再次運行它,直到它最終找到一個。

嘗試使用模塊 requests https://requests.readthedocs.io/en/master/user/quickstart/#raw-response-content您可以使用以下命令安裝它:pip install requests

編輯

它是哪個網站?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM