如何在AppleScript App中运行指定Python脚本,实现一键执行?
Absolutely! You can package your web scraping Python script into an AppleScript application that users can launch with a single click—no need for code editors like Sublime Text. Here's a step-by-step guide to make it work smoothly:
1. Prepare Python Dependencies First
Your script uses BeautifulSoup and requests, so these libraries need to be installed in the Python environment your AppleScript will use.
If you're using macOS's default Python 3 (most modern versions have this), open Terminal and run:
pip3 install beautifulsoup4 requests
If you're using a custom Python environment (like pyenv), make sure to note the full path to that Python executable—you'll need it later in your AppleScript.
2. Create the AppleScript Wrapper
Open Script Editor (found in /Applications/Utilities/), then paste this code:
-- Define paths to your script and files inside the app bundle set appResourcesFolder to POSIX path of (path to me as text) & "Contents/Resources/" set pythonScriptPath to appResourcesFolder & "scraper.py" set urlsCsvPath to appResourcesFolder & "urls.csv" set resultsCsvPath to appResourcesFolder & "results.csv" try -- Navigate to the resources folder (so relative paths in your Python script work) -- Replace /usr/bin/python3 with your actual Python path if needed do shell script "cd " & quoted form of appResourcesFolder & "; /usr/bin/python3 " & quoted form of pythonScriptPath -- Notify user when done display dialog "Scraping completed successfully! Results saved to:\n" & resultsCsvPath buttons {"OK"} default button 1 with icon note on error errMsg -- Show error message if something goes wrong display dialog "Oops, an error occurred:\n" & errMsg buttons {"Close"} default button 1 with icon stop end try
Quick Notes on the AppleScript:
- Replace
/usr/bin/python3with the path to your Python executable if you're using a non-default setup. To find your Python path, runwhich python3orwhich pythonin Terminal. - The script assumes your Python file is named
scraper.py—adjust the name in the AppleScript if you use a different filename.
3. Package Everything Into the App
- In Script Editor, go to File > Save.
- Set the File Format to Application, name your app (e.g., "WebScraper.app"), and save it somewhere accessible.
- Right-click your new app and select Show Package Contents.
- Navigate to
Contents > Resources. - Copy your Python script (rename it to
scraper.pyif needed) and yoururls.csvfile into this Resources folder.
4. Test It Out
Double-click your new app to run it. It will:
- Run in the background (no Terminal window will pop up unless you modify the AppleScript to show it)
- Use the
urls.csvinside the app bundle as input - Save
results.csvback to the Resources folder - Show a dialog when it's done (or alert you if an error occurs)
Your Original Python Script (Ready to Use)
Just save this as scraper.py and drop it into the app's Resources folder:
from bs4 import BeautifulSoup import requests import csv class_1 = {"class": "productsPicture"} class_2 = {"class": "product_content"} class_3 = {"class": "id-fix"} # map a column number to the required find parameters class_to_find = { 0 : class_3, # Not defined in question 1 : class_1, 2 : class_1, 3 : class_3, # Not defined in question 4 : class_2, 5 : class_2} with open('urls.csv', 'r') as csvFile, open('results.csv', 'w', newline='') as results: reader = csv.reader(csvFile) writer = csv.writer(results) for row in reader: # get the url output_row = [] for index, url in enumerate(row): url = url.strip() # Skip any empty URLs if len(url): #print('col: {}\nurl: {}\nclass: {}\n\n'.format(index, url, class_to_find[index])) # fetch content from server try: html = requests.get(url).content except requests.exceptions.ConnectionError as e: output_row.extend([url, '', 'bad url']) continue except requests.exceptions.MissingSchema as e: output_row.extend([url, '', 'missing http...']) continue # soup fetched content soup = BeautifulSoup(html, 'html.parser') divTag = soup.find("div", class_to_find[index]) if divTag: # Return all 'a' tags that contain an href for a in divTag.find_all("a", href=True): url_sub = a['href'] # Test that link is valid try: r = requests.get(url_sub) output_row.extend([url, url_sub, 'ok']) except requests.exceptions.ConnectionError as e: output_row.extend([url, url_sub, 'bad link']) else: output_row.extend([url, '', 'no results']) writer.writerow(output_row)
Quick Troubleshooting Tips
- If the app says "command not found" for Python: Double-check your Python path in the AppleScript.
- If
urls.csvisn't being found: Make sure it's in the Resources folder and the AppleScript is navigating to that folder with thecdcommand. - If you need to update
urls.csvlater: Just right-click the app, show package contents, and replace the file in Resources.
内容的提问来源于stack exchange,提问作者AnotherUser31

