I made a script that downloads zip-files from a website. The script needs to locate the correct link and download the file.
I generated the script with codegen and it works, buth the filename is hardcoded.
I would like the script to find the correct link, without the date (filename = "2022-09-26_TEST.zip"). So the script needs to detect the file with TEST and download it.
I can't figure out how to do this. I already tried passing a variable, but it doesn't seem to work.
How can I pass a variable to the locator and let it search on a piece of the filename (contains)?
with page.expect_download() as download_info:
page.locator("text=2022-09-26_TEST.zip").click()
download = download_info.value
page.wait_for_url("http://192.xx")
download_filepath = os.path.join(download_path, suggested_filename)
download.save_as(download_filepath)
context.close()
browser.close()
<tbody>
<tr>
<td>10386</td>
<td>TEST</td>
<td></td>
<td>491</td>
<td>finished</td>
<td>
<a class="text-primary" href="./Exports.php?downloadId=10386">2022-09-26_TEST.zip</a>
</td>
<td>2022-09-26 10:17:03</td>
<td>2022-09-26 10:18:11</td>
<td>0</td>
<td>TEST</td>
</tr>
Reading your question I understand that your problem is not the download itself, your problem is the way of clicking the link that you need.
From that moment, you have to options:
1 - You know the date (exact text):
date = "2022-09-26"
with page.expect_download() as download_info:
page.locator(f"//a[text()='{date}_TEST.zip']").click()
download = download_info.value
page.wait_for_url("http://192.xx")
download_filepath = os.path.join(download_path, suggested_filename)
download.save_as(download_filepath)
context.close()
browser.close()
As you can see you can use f"..{}.."
for your locator string in order to use some vars for the locator, basically a locator is a string.
Of course you should know the date before, in my example is hardcoded.
2 - You don't know the date (Contains text):
with page.expect_download() as download_info:
page.locator(f"//a[contains(text(),'_TEST.zip')]").click()
download = download_info.value
page.wait_for_url("http://192.xx")
download_filepath = os.path.join(download_path, suggested_filename)
download.save_as(download_filepath)
context.close()
browser.close()
And being honest, I think the line page.wait_for_url("http://192.xx")
is not needed. Playwright will wait for your download, actually you don't need to wait for the url, I think.
For my examples I used selector with Xpath.