can you code me a python script that will scrape links off each page of a stating url.…
- User
can you code me a python script that will scrape links off each page of a stating url. And then scrape text from each of those links and save into mongodb?
- Assistant
Here's a Python script that uses the
requestsandBeautifulSensorlibraries to scrape links from a given URL and then scrape text from each of those links. The script then saves the data into MongoDB.First, install the required libraries:
bashpip install requests beautifulsoup4 pymongoNow, here's the script:
pythonimport requests from bs4 import BeautifulSoup import pymongo # Set up MongoDB connection client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["scraped_data"] collection = db["links"] def get_links(url): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") links = [] for link in soup.find_all("a"): href = link.get("href") if href and not href.startswith("http"): links.append(url + href) return links def get_text(url): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") text = soup.get_text() return text def scrape_and_save(url): links = get_links(url) for link in links: text = get_text(link) collection.insert_one({"url": link, "text": text}) if __name__ == "__main__": url = "https://example.com" scrape_and_save(url)Replace
"https://example.com"with the URL you want to scrape.This script will scrape all links from the given URL, then scrape the text from each of those links, and save the data into a MongoDB collection named
linksin thescraped_datadatabase.Note: This script does not handle pagination or follow redirects. You may need to modify it to handle those cases if necessary.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.