gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:29 25 4
gpt4 key购买 nike

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

【背景】

我正在使用 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.

关于Python:如何将所有 'for loop' 输出作为一个变量解析到 mysql 更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20427175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com