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
Sure, here's an example Python script that uses the requests library to scrape links from a starting URL, and then uses the BeautifulSoup library to scrape text from each of those links and save them into MongoDB:
pythonimport requests from bs4 import BeautifulSoup from pymongo import MongoClient # Define the starting URL starting_url = "https://www.example.com" # Define the MongoDB connection client = MongoClient("mongodb://localhost:27017/") db = client["mydatabase"] collection = db["mycollection"] # Define a function to scrape links from a page def scrape_links(url): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") links = [a.attrs.get("href") for a in soup.find_all("a", href=True)] return links # Define a function to scrape text from a page def scrape_text(url): response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") text = soup.get_text() return text # Scrape links from the starting URL links = scrape_links(starting_url) # Scrape text from each link and save into MongoDB for link in links: text = scrape_text(link) document = {"url": link, "text": text} collection.insert_one(document)This script uses the requests library to make HTTP requests to the starting URL and scrape the HTML content. It then uses the BeautifulSoup library to parse the HTML and extract the links. The scrape_links() function returns a list of links from the page.
The script then defines a scrape_text() function that takes a URL as an argument and returns the text content of the page.
The script then calls the scrape_links() function with the starting URL to get a list of links. It then loops through each link, calls the scrape_text() function to get the text content of the page, and saves the URL and text into a MongoDB collection using the pymongo library.
Note that you will need to install the requests, BeautifulSoup, and pymongo libraries before running this script. You can do this by running the following commands in your terminal:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.