i'm trying to add a progress bar with rich to my code. However, while the code is running, the bar only updates to 100% after it's finished. Can I have any help? My code:
theme = Theme({'success': 'bold green',
'error': 'bold red', 'enter': 'bold blue'})
console = Console(theme=(theme))
for i in track(range(1), description='Scraping'):
global pfp
global target_id
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
begining_of_url = "https://lookup.guru/"
whole_url = begining_of_url + str(target_id)
driver.get(whole_url)
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.XPATH, "//img")))
images = driver.find_elements_by_tag_name('img')
for image in images:
global pfp
pfp = (image.get_attribute('src'))
break
if pfp == "a":
console.print("User not found \n", style='error')
userInput()
img_data = requests.get(pfp).content
with open('pfpimage.png', 'wb') as handler:
handler.write(img_data)
filePath = "pfpimage.png"
searchUrl = 'https://yandex.com/images/search'
files = {'upfile': ('blob', open(filePath, 'rb'), 'image/jpeg')}
params = {'rpt': 'imageview', 'format': 'json',
'request': '{"blocks":[{"block":"b-page_type_search-by-image__link"}]}'}
response = requests.post(searchUrl, params=params, files=files)
query_string = json.loads(response.content)[
'blocks'][0]['params']['url']
img_search_url = searchUrl + '?' + query_string
webbrowser.open(whole_url)
webbrowser.open(img_search_url)
console.print("Done!", style='success')
Edit:
For more clarity, I want the progressbar to update as it goes through each part of my code. There is only one url to scrape. For example it would start at 0%, and after global pfp
the bar would change to x%
Thanks for any help :)
The problem was that through the use of
for i in track(range(1), description='Scraping'):
the bar would only go to 100% when the loop had finished. By changing therange()
value would make the code loop and would update the bar. To fix this issue I used another rich module calledProgress
.By importing
Progress
and then modifying the code on the Rich Documentation I got:Essentially:
task1 = progress.add_task("[red]Scraping", total=100)
a bar is created with a maximum value of 100while not progress.finished:
will loop until the bar is at 100%progress.update(task1, advance=0.5)
the bar's total will be increased by a value of 0.5.Therefore, for my specific example, my end result code was: