为什么 replace() 函数不起作用?

Why isn't the replace() function working?

我正在使用 Selenium 抓取网站。当我获得元素列表的文本 (headers) 时,它会打印出以下内容:

    ['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 替换为空字符串。这是我的代码:

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() 函数不起作用。

非常感谢您的帮助!

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

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