靓汤:替换返回的图像源的一部分

2024-06-13 19:16:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python和beautiful soup都是新手,所以为了练习,我制作了一个图像刮刀,它大部分都能工作。我可以找到这些图片,下载到我的电脑上,然后根据它们的名字把它们放到文件夹里。但我遇到了一个问题。这是我的密码

import requests
from bs4 import BeautifulSoup
import os.path

url = "https://example.net/g/1"
i = 1
data = requests.get(url)

soup = BeautifulSoup(data.text, 'html.parser')
for sou in soup.findAll("div", {"class": "gallery"}):
    sou.decompose()

containers = soup.find_all('img')
title = soup.find('h1').text
imgsrc = containers

for imgs in imgsrc: 
    if ".jpg" in imgs['src']:
        sauce = (imgs['src'])

        if sauce[:1] =="/":
          image = 'https:' + sauce
        else:
          image = sauce

        nametemp = imgs.get('alt')
        if nametemp is None:
                filename = str(i)
                i = i+1
                print(image)

当我运行这个,我得到这些图像源

  1. https://t.example.net/galleries/9/cover.jpg
  2. https://t.example.net/galleries/9/1t.jpg
  3. https://t.example.net/galleries/9/2t.jpg

这是我想要的大部分,但返回的源代码是缩略图,所以它们很小。要获得全尺寸的图像,这很容易。只需更换两个T

我的问题是如何用这个替换上面的内容

  1. https://i.example.net/galleries/9/1.jpg
  2. https://i.example.net/galleries/9/2.jpg

我试着使用replace_with(),并查看了文档,但我对它有一点了解。你知道吗


Tags: inhttps图像imageimportnetifexample
1条回答
网友
1楼 · 发布于 2024-06-13 19:16:53

你的代码很混乱,与你的问题无关。因此,假设您有一个名为thumbnails的URL列表:

thumbnails = [
    'https://t.example.net/galleries/9/1t.jpg',
    'https://t.example.net/galleries/9/2t.jpg',
    'https://t.example.net/galleries/9/3t.jpg',
]

然后,您可以在列表中使用regex replace来转换您想要的URL:

import re
images = [re.sub(r't(\.jpg)', r'\1', url) for url in thumbnails]

相关问题 更多 >