为什么 replace() 函数不起作用? [英] Why isn't the replace() function working?

查看:27
本文介绍了为什么 replace() 函数不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Selenium 抓取网站.当我获得元素列表(标题)的文本时,它会打印:

I'm scraping a website using Selenium. When I get the text of a list of elements (headers), this is what it prints:

    ['Countyarrow_upward Reportingarrow_upward Totalarrow_upward Bennet (D)arrow_upward Biden (D)arrow_upward Bloomberg (D)arrow_upward Booker (D)arrow_upward Boyd (D)arrow_upward Buttigieg (D)arrow_upward 
Castro (D)arrow_upward De La Fuente III (D)arrow_upward Delaney (D)arrow_upward Ellinger (D)arrow_upward Gabbard (D)arrow_upward Greenstein (D)arrow_upward Klobuchar (D)arrow_upward Patrick (D)arrow_upw
ard Sanders (D)arrow_upward Sestak (D)arrow_upward Steyer (D)arrow_upward Warren (D)arrow_upward Williamson (D)arrow_upward Yang (D)arrow_upward']

我显然只想要名称和(D)",所以我尝试使用 replace() 函数将 Countyarrow_upward Reportingarrow_upward Totalarrow_upwardarrow_upward 替换为空字符串.这是我的代码:

I obviously only want the names and the "(D)", so I tried using the replace() function to replace the Countyarrow_upward Reportingarrow_upward Totalarrow_upward and arrow_upward with an empty string. Here's my code:

headers = driver.find_elements_by_xpath('//*[@id="content"]/div/div[3]/div/div[2]/div/div[2]/div/div[2]/div[1]/div/table/thead/tr[1]')
    header_text = []
    for i in headers:
        header_raw_text = i.text
        header_raw_text.replace("Countyarrow_upward Reportingarrow_upward Totalarrow_upward ", "")
        header_raw_text.replace("arrow_upward ", "")
        header_text.append(header_raw_text)

    print(header_text)

当我运行这段代码时,我得到了与上面相同的结果,并且 replace() 函数不起作用.

When I run this code, I get the same thing above, and the replace() function doesn't work.

非常感谢帮助!

推荐答案

字符串是不可变的.所以 header_raw_text.replace() 不会改变字符串本身.你必须在替换后重新分配结果.

strings are immutable. so header_raw_text.replace() does not change the string itself.you have to do reassign the result after replacing.

header_raw_text = header_raw_text.replace("arrow_upward ", "")

这篇关于为什么 replace() 函数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆