我正在使用 Selenium 抓取一个网站。当我获取元素列表(标题)的文本时,它会打印以下内容:
['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_upward
and arrow_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()
不会更改字符串本身。替换后必须重新分配结果。
header_raw_text = header_raw_text.replace("arrow_upward ", "")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)