I want to remove all special characters in name
, but i did a dirty code. Someone know a better way for help me?
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Set driver and time for wait in chrome
driver = webdriver.Chrome(executable_path=r"C:\Users\Gabri\anaconda3\chromedriver.exe")
wait: WebDriverWait = WebDriverWait(driver, 20)
# Open music link
driver.get('https://youtu.be/IJvV7qy0xQM')
# Set xpath of music name
Name_Music_xpath = '//*[@id="container"]/h1/yt-formatted-string'
# Waits until name appears
wait.until(EC.visibility_of_element_located((By.XPATH, Name_Music_xpath)))
# Save name
name = driver.find_element_by_xpath(Name_Music_xpath)
Original_name = name.text
Formatted_name = name.text
# I want to format music name but, i just know this way to make it
# I need to clear, removing everything that is not letter like () & . -
Formatted_name = Formatted_name.replace(')', '')
Formatted_name = Formatted_name.replace('(', '')
Formatted_name = Formatted_name.replace('&', '')
Formatted_name = Formatted_name.replace('.', '')
Formatted_name = Formatted_name.replace('-', '')
# Print the original name, and the format that i need
print(Original_name)
print(Formatted_name)
SOLVED CODE:
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Function to remove special characters
def remove_chars(input: str):
cleaned_input = re.sub(r'[()&.-]', '', input)
return " ".join(cleaned_input.split())
# Set driver and time for wait in chrome
driver = webdriver.Chrome(executable_path=r"C:\Users\Gabri\anaconda3\chromedriver.exe")
wait: WebDriverWait = WebDriverWait(driver, 20)
# Open music link
driver.get('https://youtu.be/IJvV7qy0xQM')
# Set xpath of music name
Name_Music_xpath = '//*[@id="container"]/h1/yt-formatted-string'
# Waits until name appears
wait.until(EC.visibility_of_element_located((By.XPATH, Name_Music_xpath)))
# Save name
name = driver.find_element_by_xpath(Name_Music_xpath)
Original_name = name.text
Formatted_name = remove_chars(name.text)
print(Original_name)
print(Formatted_name)