I have a list of URLs. I need to retrieve the titles of the webpage of each URL and save them both in a csv. Use python
Assistant
To retrieve the titles of web pages from a list of URLs and save them in a CSV file using Python, you can use the requests library to fetch the content of the pages and the BeautifulSoup library to parse the HTML and extract the titles. Finally, you can use the csv library to save the URLs and their corresponding titles in a CSV file.
Here is a complete example:
Make sure you have the necessary libraries installed. You can install them using pip:
bash
pip install requests beautifulsoup4
Use the following Python code to fetch titles and save them to a CSV file:
python
import requests
from bs4 import BeautifulSoup
import csv
# List of URLs to retrieve titles from
urls = [
'https://www.example.com',
'https://www.wikipedia.org',
'https://www.python.org',
# Add more URLs as needed
]
# Function to fetch the title of a webpage
def fetch_title(url):
try:
response = requests.get(url)
response.raise_for_status() # Check for request errors
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string.strip() if soup.title else 'No title found'
return title
except Exception as e:
return f'Error: {str(e)}'
# Creating a list to hold URLs and their titles
url_titles = []
# Fetch titles for each URL
for url in urls:
title = fetch_title(url)
url_titles.append((url, title))
# Save the URLs and titles in a CSV file
with open('url_titles.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['URL', 'Title']) # Write header
writer.writerows(url_titles) # Write the data
print('Titles have been fetched and saved to url_titles.csv')
Explanation of the Code:
Libraries: The code imports the necessary libraries (requests, BeautifulSoup, and csv).
URLs List: You define a list of URLs (urls) that you want to process.
fetch_title Function: This function takes a URL as input, makes a GET request to the URL, and attempts to extract the title from the returned HTML. If any error occurs (like a network error or a page not found), it returns an error message.
Collecting Titles: The code iterates over each URL in the list, calling the fetch_title function and appending the (URL, Title) pair to the url_titles list.
Writing to CSV: Finally, it writes the collected URL and title pairs into a CSV file called url_titles.csv.
Note:
Make sure that you have permission to scrape the web pages you're accessing, as some websites prohibit scraping in their robots.txt.
Always check the website policies and be respectful of their usage limits (e.g., rate limiting).
User
use pandas instead
Assistant
Sure! You can use the pandas library to handle the data more efficiently and save it in a CSV format. Below is the modified code that uses pandas instead of the csv library.
Make sure you have the necessary libraries installed. You can install them using pip if you haven't done so:
bash
pip install requests beautifulsoup4 pandas
Use the following Python code to fetch titles and save them to a CSV file using pandas:
python
import requests
from bs4 import BeautifulSoup
import pandas as pd
# List of URLs to retrieve titles from
urls = [
'https://www.example.com',
'https://www.wikipedia.org',
'https://www.python.org',
# Add more URLs as needed
]
# Function to fetch the title of a webpage
def fetch_title(url):
try:
response = requests.get(url)
response.raise_for_status() # Check for request errors
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string.strip() if soup.title else 'No title found'
return title
except Exception as e:
return f'Error: {str(e)}'
# Creating a list to hold URLs and their titles
url_titles = []
# Fetch titles for each URL
for url in urls:
title = fetch_title(url)
url_titles.append({'URL': url, 'Title': title})
# Convert the list of dictionaries to a DataFrame
df = pd.DataFrame(url_titles)
# Save the DataFrame to a CSV file
df.to_csv('url_titles.csv', index=False, encoding='utf-8')
print('Titles have been fetched and saved to url_titles.csv')
Explanation of the Code:
Imports: The code imports requests, BeautifulSoup from bs4, and pandas.
URLs List: You define a list of URLs to process.
fetch_title Function: This function is unchanged; it fetches the title of each webpage.
Collecting Titles: Instead of a list of tuples, the code now appends dictionaries to url_titles, where each dictionary contains 'URL' and 'Title' keys.
Creating DataFrame: The list of dictionaries is converted to a pandas DataFrame using pd.DataFrame().
Exporting to CSV: The DataFrame is saved to a CSV file named url_titles.csv using .to_csv().
By using pandas, the code becomes more readable, and it takes advantage of the powerful data manipulation capabilities of the library.
User
read the urls from a csv
Assistant
To read the URLs from a CSV file instead of defining them directly in the code, you'll need to modify the script to read the input CSV file first. Below are steps to do so, along with the modified code.
Ensure you have a CSV file that contains the URLs. Let's assume this file is named input_urls.csv and has a single column named URL.
Modify the code as follows to read URLs from the CSV file:
python
import requests
from bs4 import BeautifulSoup
import pandas as pd
# Read URLs from the input CSV file
input_csv_file = 'input_urls.csv'
url_df = pd.read_csv(input_csv_file)
# Ensure the column with URLs is named 'URL'
urls = url_df['URL'].tolist()
# Function to fetch the title of a webpage
def fetch_title(url):
try:
response = requests.get(url)
response.raise_for_status() # Check for request errors
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string.strip() if soup.title else 'No title found'
return title
except Exception as e:
return f'Error: {str(e)}'
# Creating a list to hold URLs and their titles
url_titles = []
# Fetch titles for each URL
for url in urls:
title = fetch_title(url)
url_titles.append({'URL': url, 'Title': title})
# Convert the list of dictionaries to a DataFrame
df = pd.DataFrame(url_titles)
# Save the DataFrame to a CSV file
output_csv_file = 'url_titles.csv'
df.to_csv(output_csv_file, index=False, encoding='utf-8')
print(f'Titles have been fetched and saved to {output_csv_file}')
Changes Made:
Reading the Input CSV:
The script uses pd.read_csv('input_urls.csv') to read the URLs from the input CSV file.
It assumes that the column containing the URLs is named URL. Change this if your column name is different.
Storing URLs:
The URLs are extracted into a list using url_df['URL'].tolist().
Output File:
The output file name is stored in output_csv_file for easier modification.
Usage:
Save the input CSV containing your URLs in the same directory where your script is located or provide the full path to the CSV file.
Run the script, and it will read the URLs, fetch their titles, and save the results in url_titles.csv.
User
I'll give you a list of URLs. Extract the titles from the last /
To extract titles from the last segment of each URL (the part after the last /), you can process the list of URLs and extract the relevant segments accordingly. Below is a Python script that performs this task:
It takes the given URLs.
It extracts the last segment of each URL to use it as a title for that entry.
Finally, it saves the results in a CSV file.
Here's how you can implement it:
python
import pandas as pd
# List of URLs
urls = [
"https://www.reddit.com/r/LocalLLaMA/comments/16zuccy/after_500_loras_made_here_is_the_secret",
"https://www.reddit.com/r/StableDiffusion/comments/123s93x/whats_lora",
"https://www.reddit.com/r/StableDiffusion/comments/10i81s3/what_is_a_lora_and_how_do_i_use_it_effectively",
"https://www.datacamp.com/tutorial/llama-index-adding-personal-data-to-llms",
"https://www.reddit.com/r/MachineLearning/comments/yzzxa2/d_why_do_we_train_language_models_with_next_word",
"https://www.reddit.com/r/LocalLLaMA/comments/15zz81s/llama2_quantized_model_vs_regular_one_whats_the",
"https://www.datacamp.com/blog/what-is-retrieval-augmented-generation-rag",
"https://www.datacamp.com/blog/what-is-bert-an-intro-to-bert-models",
"https://www.reddit.com/r/LanguageTechnology/comments/139ps2e/llms_sentence_embeddings_for_sentence_similiarity",
"https://www.promptingguide.ai/techniques/prompt_chaining",
"https://www.datacamp.com/blog/what-is-bert-an-intro-to-bert-models",
"https://www.datacamp.com/courses/feature-engineering-for-nlp-in-python",
"https://www.datacamp.com/blog/understanding-and-mitigating-bias-in-large-language-models-llms",
"https://www.datacamp.com/tutorial/fine-tuning-large-language-models"
]
# Creating a list to hold the URLs and their extracted titles
url_titles = []
# Extract titles from the last segment of each URL
for url in urls:
title = url.split('/')[-1] # Get the last segment after the last '/'
url_titles.append({'URL': url, 'Title': title})
# Convert the list of dictionaries to a DataFrame
df = pd.DataFrame(url_titles)
# Save the DataFrame to a CSV file
output_csv_file = 'url_titles.csv'
df.to_csv(output_csv_file, index=False, encoding='utf-8')
print(f'Titles have been extracted and saved to {output_csv_file}')
User
dont give me code. extract it yurself
Assistant
Sure! Here are the titles extracted from the URLs you provided, taken from the last segment of each URL:
If you have any further instructions or need more information, feel free to ask!
User
convert the titles into sentences with proper punct
Assistant
Sure! Here are the extracted titles converted into complete sentences with proper punctuation:
"After 500 Loras made, here is the secret."
"What is Lora?"
"What is a Lora and how do I use it effectively?"
"Llama index: Adding personal data to LLMs."
"Why do we train language models with next word?"
"Llama2 quantized model vs. regular one: What's the difference?"
"What is retrieval-augmented generation (RAG)?"
"What is BERT? An introduction to BERT models."
"LLMs: Sentence embeddings for sentence similarity."
"Prompt chaining."
"What is BERT? An introduction to BERT models."
"Feature engineering for NLP in Python."
"Understanding and mitigating bias in large language models (LLMs)."
"Fine-tuning large language models."
If you need further modifications or assistance, just let me know!
User
no bullets or "
Assistant
Sure! Here are the titles converted into sentences without bullets or quotation marks:
After 500 Loras made, here is the secret.
What is Lora?
What is a Lora and how do I use it effectively?
Llama index: Adding personal data to LLMs.
Why do we train language models with next word?
Llama2 quantized model vs. regular one: What's the difference?
What is retrieval-augmented generation (RAG)?
What is BERT? An introduction to BERT models.
LLMs: Sentence embeddings for sentence similarity.
Prompt chaining.
What is BERT? An introduction to BERT models.
Feature engineering for NLP in Python.
Understanding and mitigating bias in large language models (LLMs).
Fine-tuning large language models.
List of URLs: The script contains a predefined list of URLs.
Extracting Titles: Using a loop, the last segment of each URL is extracted using url.split('/')[-1], which splits the URL into parts based on the / delimiter and retrieves the last part.
Storing Results: Each URL and its extracted title are stored as a dictionary in the url_titles list.
Creating a DataFrame: The list of dictionaries is converted into a pandas DataFrame.
Saving to CSV: Finally, the DataFrame is saved to a CSV file named url_titles.csv.
Output:
After running the script, you'll get a CSV file named url_titles.csv that contains two columns: URL and Title, where the Title corresponds to the last segment of the URL after the last /.