Skip to main content
 首页 » 编程设计

Python:如何将所有 'for loop' 输出作为一个变量解析到 mysql 更新查询

2025年05月04日15artech

您好,我一直在寻找类似的主题,但找不到,所以发帖提问。任何帮助将不胜感激。

【背景】

我正在使用 beautifulsoup 来抓取一些网站。我想要实现的是在 html (ex./examplefolder/image/) 中找到具有特定相对路径的图像,并通过添加前缀 (ex.xxx.example.com) 将其转换为明确的路径,然后解析一个包含'for循环'到mysql更新查询的结果(多个实例)的变量。

【当前代码】

import urlparse 
#find relative path in html doc 
for image in soup.select('img[src^="/examplefolder/image/"]'): 
    #extract src value 
    path = "%(src)s" % image 
    #define base url 
    base_url = "xxx.example.com" 
    #add it together 
    image = urlparse.urljoin(base_url, path) 

【问题】

当我在控制台上执行上面的脚本时,它会返回所有图像路径,到目前为止还不错,但是,如果我在 mysql 查询中使用“图像”作为变量,它只会保存最后一个值

示例输出:

xxx.example.com/examplefolder/image/1.jpg

xxx.example.com/examplefolder/image/2.jpg

xxx.example.com/examplefolder/image/3.jpg

xxx.example.com/examplefolder/image/4.jpg

xxx.example.com/examplefolder/image/5.jpg <- only the last value gets stored

这仅仅是因为 'image' 只包含最后一个值,因为 for 循环每次循环都会为 'image' 分配新值。

【问题】

因为我想将图像存储在 mysql 表中的一个字段(行)中,所以我需要“图像”变量来包含所有 5 jpg 图像输出。

类似于: 图片= xxx.example.com/examplefolder/image/1.jpg, xxx.example.com/examplefolder/image/2.jpg, xxx.example.com/examplefolder/image/3.jpg, xxx.example.com/examplefolder/image/4.jpg, xxx.example.com/examplefolder/image/5.jpg

所以我可以将“图像”变量解析为 mysql 查询。

我不知道如何实现这一目标。

如果您知道或可以给我一些提示,我将不胜感激。

提前致谢。

请您参考如下方法:

How to parse all the 'for loop' outputs to mysql update query as one variable

您可以使用列表。列表对象将是一个变量。

imgList = [] 
for image in soup.select('img[src^="/examplefolder/image/"]'): 
    .. 
    .. 
    image = urlparse.urljoin(base_url, path) 
    imgList.append(image) 
 
# Use the list: imgList 
print imgList  #Display the array of all the images you extracted.     
 
#Construct your SQL query to insert the images.