change this gig tags extractor porgram to getting information about the pricing of these gigs incluing basic advanced and 3rd pacage import requests
from bs4 import BeautifulSoup
import time
import logging
def read_urls(file_path):
"""
Reads URLs from a specified text file.
Each URL should be on a separate line.
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
urls = file.read().splitlines()
# Clean and filter out empty lines
urls = [url.strip() for url in urls if url.strip()]
logging.info(f"Successfully read {len(urls)} URLs from {file_path}.")
return urls
except FileNotFoundError:
logging.error(f"File {file_path} not found.")
raise
except Exception as e:
logging.error(f"Error reading {file_path}: {e}")
raise
def extract_tags(html_content, url):
"""
Extracts related tags from the HTML content.
code
Parameters:
html_content (str): The HTML content of the webpage.
url (str): The URL of the webpage (for debugging purposes).
Returns:
list: A list of related tags.
"""
soup = BeautifulSoup(html_content, 'html.parser')
tags = []
try:
# Find the div with class 'gig-tags-container'
tags_container = soup.find('div', class_='gig-tags-container')
if tags_container:
# Find all <a> tags within <li> elements inside the container
tag_elements = tags_container.find_all('a')
tags = [tag.get_text(strip=True) for tag in tag_elements if tag.get_text(strip=True)]
if not tags:
logging.warning(f"No tags found in gig-tags-container for URL: {url}")
else:
logging.warning(f"'gig-tags-container' div not found for URL: {url}")
except Exception as e:
logging.error(f"Error extracting tags for URL {url}: {e}")
return tags
def process_urls(urls, output_file):
"""
Processes each URL to extract related tags and write them to an output file.
code
Assistant
Parameters:
urls (list): List of Fiverr gig URLs.
output_file (str): Path to the output text file.
"""
headers = {
'User-Agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/90.0.4430.93 Safari/537.36'
)
}
with open(output_file, 'w', encoding='utf-8') as f_out:
for idx, url in enumerate(urls, 1):
print(f"Processing ({idx}/{len(urls)}): {url}")
try:
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status() # Raise HTTPError for bad responses
tags = extract_tags(response.text, url)
# Write extracted tags to the output file
f_out.write(f"URL {idx}: {url}\n")
f_out.write("Related Tags:\n")
if tags:
for tag in tags:
f_out.write(f"- {tag}\n")
else:
f_out.write("No related tags found.\n")
f_out.write("="*80 + "\n\n")
# Log successful extraction
logging.info(f"Successfully processed URL {idx}: {url}")
# Politeness delay to avoid overwhelming the server
time.sleep(1)
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred for {url}: {http_err}")
logging.error(f"HTTP error for URL {idx} ({url}): {http_err}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"HTTP Error: {http_err}\n")
f_out.write("="*80 + "\n\n")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred for {url}: {conn_err}")
logging.error(f"Connection error for URL {idx} ({url}): {conn_err}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"Connection Error: {conn_err}\n")
f_out.write("="*80 + "\n\n")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error for {url}: {timeout_err}")
logging.error(f"Timeout error for URL {idx} ({url}): {timeout_err}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"Timeout Error: {timeout_err}\n")
f_out.write("="*80 + "\n\n")
except requests.exceptions.RequestException as req_err:
print(f"Request exception for {url}: {req_err}")
logging.error(f"Request exception for URL {idx} ({url}): {req_err}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"Request Exception: {req_err}\n")
f_out.write("="*80 + "\n\n")
except Exception as e:
print(f"An unexpected error occurred for {url}: {e}")
logging.error(f"Unexpected error for URL {idx} ({url}): {e}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"Unexpected Error: {e}\n")
f_out.write("="*80 + "\n\n")
def main():
"""
Main function to orchestrate the scraping process.
"""
# Input and output file paths
url_file = 'urls.txt'
output_file = 'extracted_tags.txt'
code
try:
urls = read_urls(url_file)
if not urls:
print(f"No URLs found in {url_file}. Please add URLs, one per line.")
logging.error(f"No URLs to process. {url_file} is empty.")
return
except Exception as e:
print(f"Error reading URLs: {e}")
return
process_urls(urls, output_file)
print(f"Extraction complete. Check the '{output_file}' file for results.")
print(f"Refer to 'scraper.log' for detailed logs.")
if name == "main":
main()
ELEMT FOR PRICING BasicStandardPremiumConsulting CallPKR 29,240On this 1 hour call, I will sit down with you and help refine your idea then provide a quote.2-day deliveryResearchModel creationModel documentationContinueCompare packages
Certainly! I'll help you modify your existing tags extractor program to extract pricing information for Fiverr gigs, including the Basic, Standard, and Premium packages. Below is the updated script with detailed explanations and comments to guide you through the changes.
Updated Script: price_extractor.py
python
import requests
from bs4 import BeautifulSoup
import time
import logging
# Configure logging
logging.basicConfig(
filename='scraper.log',
filemode='a',
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
def read_urls(file_path):
"""
Reads URLs from a specified text file.
Each URL should be on a separate line.
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
urls = file.read().splitlines()
# Clean and filter out empty lines
urls = [url.strip() for url in urls if url.strip()]
logging.info(f"Successfully read {len(urls)} URLs from {file_path}.")
return urls
except FileNotFoundError:
logging.error(f"File {file_path} not found.")
raise
except Exception as e:
logging.error(f"Error reading {file_path}: {e}")
raise
def extract_prices(html_content, url):
"""
Extracts pricing information for Basic, Standard, and Premium packages from the HTML content.
Parameters:
html_content (str): The HTML content of the webpage.
url (str): The URL of the webpage (for debugging purposes).
Returns:
dict: A dictionary containing package names as keys and their respective prices as values.
"""
soup = BeautifulSoup(html_content, 'html.parser')
prices = {}
try:
# Locate the div containing package information
packages_div = soup.find('div', class_='packages-tabs triple')
if not packages_div:
logging.warning(f"'packages-tabs triple' div not found for URL: {url}")
return prices # Return empty dict if not found
# Extract package names from the navigation labels
nav_container = packages_div.find('div', class_='nav-container')
if not nav_container:
logging.warning(f"'nav-container' div not found within 'packages-tabs triple' for URL: {url}")
return prices
labels = nav_container.find_all('label', class_='new-pro-layout')
package_names = [label.get_text(strip=True) for label in labels if label.get_text(strip=True)]
if not package_names:
logging.warning(f"No package labels found within 'nav-container' for URL: {url}")
return prices
# Extract all price spans within the packages
price_spans = packages_div.find_all('span', class_='price')
prices_list = [span.get_text(strip=True) for span in price_spans if span.get_text(strip=True)]
if not prices_list:
logging.warning(f"No price information found within 'packages-tabs triple' for URL: {url}")
return prices
# Map package names to their corresponding prices based on order
for name, price in zip(package_names, prices_list):
prices[name] = price
# Log if some packages do not have corresponding prices
if len(package_names) > len(prices_list):
logging.warning(f"Number of packages ({len(package_names)}) and prices ({len(prices_list)}) do not match for URL: {url}")
except Exception as e:
logging.error(f"Error extracting prices for URL {url}: {e}")
return prices
def process_urls(urls, output_file):
"""
Processes each URL to extract pricing information and writes them to an output file.
Parameters:
urls (list): List of Fiverr gig URLs.
output_file (str): Path to the output text file.
"""
headers = {
'User-Agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/90.0.4430.93 Safari/537.36'
)
}
with open(output_file, 'w', encoding='utf-8') as f_out:
for idx, url in enumerate(urls, 1):
print(f"Processing ({idx}/{len(urls)}): {url}")
try:
response = requests.get(url, headers=headers, timeout=15)
response.raise_for_status() # Raise HTTPError for bad responses
prices = extract_prices(response.text, url)
# Write extracted prices to the output file
f_out.write(f"URL {idx}: {url}\n")
f_out.write("Package Prices:\n")
if prices:
for package, price in prices.items():
f_out.write(f"- {package}: {price}\n")
else:
f_out.write("No pricing information found.\n")
f_out.write("="*80 + "\n\n")
# Log successful extraction
logging.info(f"Successfully processed URL {idx}: {url}")
# Politeness delay to avoid overwhelming the server
time.sleep(1)
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred for {url}: {http_err}")
logging.error(f"HTTP error for URL {idx} ({url}): {http_err}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"HTTP Error: {http_err}\n")
f_out.write("="*80 + "\n\n")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred for {url}: {conn_err}")
logging.error(f"Connection error for URL {idx} ({url}): {conn_err}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"Connection Error: {conn_err}\n")
f_out.write("="*80 + "\n\n")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error for {url}: {timeout_err}")
logging.error(f"Timeout error for URL {idx} ({url}): {timeout_err}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"Timeout Error: {timeout_err}\n")
f_out.write("="*80 + "\n\n")
except requests.exceptions.RequestException as req_err:
print(f"Request exception for {url}: {req_err}")
logging.error(f"Request exception for URL {idx} ({url}): {req_err}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"Request Exception: {req_err}\n")
f_out.write("="*80 + "\n\n")
except Exception as e:
print(f"An unexpected error occurred for {url}: {e}")
logging.error(f"Unexpected error for URL {idx} ({url}): {e}")
f_out.write(f"URL {idx}: {url}\n")
f_out.write(f"Unexpected Error: {e}\n")
f_out.write("="*80 + "\n\n")
def main():
"""
Main function to orchestrate the scraping process.
"""
# Input and output file paths
url_file = 'urls.txt'
output_file = 'extracted_prices.txt'
try:
urls = read_urls(url_file)
if not urls:
print(f"No URLs found in {url_file}. Please add URLs, one per line.")
logging.error(f"No URLs to process. {url_file} is empty.")
return
except Exception as e:
print(f"Error reading URLs: {e}")
return
process_urls(urls, output_file)
print(f"Extraction complete. Check the '{output_file}' file for results.")
print(f"Refer to 'scraper.log' for detailed logs.")
if __name__ == "__main__":
main()
Explanation of Changes
Function Renaming and Purpose:
Renamed extract_tags to extract_prices: The primary purpose of the function has shifted from extracting tags to extracting pricing information.
Extracting Package Names and Prices:
Locate the Packages Container: The script locates the div with the class packages-tabs triple, which contains all the package information.
Extract Package Names: Within this container, it finds the nav-container div and retrieves all package names (e.g., Basic, Standard, Premium) from the label elements.
Extract Prices: It then finds all span elements with the class price within the same container to get the corresponding prices.
Mapping Names to Prices: The script maps each package name to its corresponding price based on their order of appearance. This assumes that the order of package names matches the order of prices in the HTML structure.
Output Formatting:
Structured Output: The output file extracted_prices.txt will now contain a clear and structured list of package names along with their prices for each URL.
Error Handling: If any discrepancies occur between the number of package names and prices, the script logs a warning.
Logging and Error Handling:
Enhanced Logging: The logging messages have been updated to reflect the changes in functionality, providing clearer insights into the scraping process.
Comprehensive Error Handling: The script includes extensive error handling to capture and log various exceptions that might occur during the scraping process.
Delays Between Requests:
Politeness Delay: A time.sleep(1) ensures that the scraper doesn't overwhelm the server with rapid requests.
Sample Output
Your extracted_prices.txt will look something like this:
code
URL 1: https://www.fiverr.com/some-gig-url
Package Prices:
- Basic: PKR 29,240
- Standard: PKR 45,360
- Premium: PKR 60,480
================================================================================
URL 2: https://www.fiverr.com/another-gig-url
Package Prices:
- Basic: PKR 15,000
- Standard: PKR 30,000
- Premium: PKR 45,000
================================================================================
Additional Recommendations
Verify the HTML Structure:
Fiverr's website structure might change over time. Ensure that the class names like packages-tabs triple, nav-container, and price are still accurate. If Fiverr updates their HTML structure, you'll need to adjust the script accordingly.
Handling Dynamic Content:
If some pricing information is loaded dynamically via JavaScript and isn't present in the initial HTML response, BeautifulSoup won't be able to extract it. In such cases, consider using tools like Selenium or Playwright that can render JavaScript.
Respect Fiverr’s Terms of Service:
Always ensure that your scraping activities comply with Fiverr's Terms of Service and Robots.txt. Unauthorized scraping can lead to IP bans or legal consequences.
Scaling the Scraper:
For a large number of URLs, consider implementing concurrency with libraries like asyncio or concurrent.futures to speed up the scraping process while still respecting Fiverr's server load.
Data Validation:
Implement additional validation checks to ensure that the extracted prices are in the expected format (e.g., proper currency symbols, numerical values).
Running the Script
Prepare the urls.txt File:
Create a urls.txt file in the same directory as your script.
Ensure you have the necessary Python libraries installed. You can install them using pip:
bash
pip install requests beautifulsoup4
Execute the Script:
Run the script using Python:
bash
python price_extractor.py
Check Outputs:
After completion, check extracted_prices.txt for the extracted pricing information.
Refer to scraper.log for detailed logs and any potential errors encountered during the scraping process.
Conclusion
This updated script should effectively extract the pricing information for Basic, Standard, and Premium packages from Fiverr gig URLs. Ensure to monitor the logs for any errors and adjust the script as needed based on changes to Fiverr's website structure.
If you encounter any issues or have further questions, feel free to ask!