我想将元素从Web元素转换为字符串,并将其发送到另一个函数并在文件名中使用它.我试了很多方法,但都失败了.我正在寻找如何做这件事的 idea .在我的代码下面.

product_title = None

def product_title():
    global product_title
    product_title = driver.find_element(By.CSS_SELECTOR, "#GoodsBlock > table > tbody > tr:nth-child(1) > td.product-title > div > a")
    print(product_title.text)
    product_title.click()


def write_txt():
    file = open("games_files/"+product_title+".txt", "w")

product_title()
write_txt()

和错误

Traceback (most recent call last):
  File "D:\python\xbox\pythonProject\scrap_games.py", line 48, in <module>
    write_txt()
  File "D:\python\xbox\pythonProject\scrap_games.py", line 41, in write_txt
    file = open("games_files/"+product_title.text+".txt", "w")
                               ^^^^^^^^^^^^^^^^^^

我试了很多方法,但都失败了.我正在寻找如何做这件事的 idea .

推荐答案

我没有大量使用selenium,但这应该可以解决这个问题.与使用全局字符串和+字符串不同,切换到Return和f字符串有助于在def之间移动信息.这是主要问题,因为您的代码没有设置product_title变量.

try :

def get_product_title():
    product_title = driver.find_element(By.CSS_SELECTOR, "#GoodsBlock > table > tbody > tr:nth-child(1) > td.product-title > div > a")    
    print(product_title.text)
    product_title.click()
    return product_title.text


def write_txt():
    file = open(f"games_files/{product_title}.txt", "w")

product_title = get_product_title()
write_txt()

我已经改变了def的名称,以便更清楚地帮助分解我的答案.product_titleget_product_title中获取product_title.text的返回值,从你的注释中这包含了你想要的值.这就省go 了在你的def中担心global的麻烦.

write_txt现在有一个f字符串,它插入变量product_title,而不需要+‘S.

EDIT: Emoji removal version

基于这里的答案:https://stackoverflow.com/a/50602709/22669764

编辑#2:将product_title.text包装在str中,并使其成为变量,以防product_title.click()对值做任何事情.添加了lstriprstrip,希望减轻表情符号的杀戮.

使用pip install emoji安装emoji包

import emoji

def get_product_title():
    product_title = driver.find_element(By.CSS_SELECTOR, "#GoodsBlock > table > tbody > tr:nth-child(1) > td.product-title > div > a")
    title = str(product_title.text)
    print(title)
    product_title.click()
    return title
    
def give_emoji_free_text(text):
    return str(emoji.replace_emoji(text, replace='')).lstrip().rstrip()

def write_txt():
    file = open(f"games_files/{clean_title}.txt", "w")

product_title = get_product_title()
clean_title = give_emoji_free_text(product_title)
write_txt()

希望这对你有用,如果是这样的话,请抬高票数,并标记为已回答.

Python相关问答推荐

当密钥是复合且唯一时,Pandas合并抱怨标签不唯一

仅从风格中获取 colored颜色 循环

三个给定的坐标可以是矩形的点吗

Pandas实际上如何对基于自定义的索引(integer和非integer)执行索引

如何制作10,000年及以后的日期时间对象?

使用Python从URL下载Excel文件

numpy.unique如何消除重复列?

在Admin中显示从ManyToMany通过模型的筛选结果

PYTHON、VLC、RTSP.屏幕截图不起作用

ModuleNotFoundError:没有模块名为x时try 运行我的代码''

计算空值

pandas fill和bfill基于另一列中的条件

无法在Spyder上的Pandas中将本地CSV转换为数据帧

极柱内丢失类型信息""

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

大型稀疏CSR二进制矩阵乘法结果中的错误

.awk文件可以使用子进程执行吗?

在MongoDB文档中仅返回数组字段

如何在表单中添加管理员风格的输入(PDF)

为什么在更新Pandas 2.x中的列时,数据类型不会更改,而在Pandas 1.x中会更改?