create a code in python beautifulsoup that scrapes a website with multiple pages by css…
- User
create a code in python beautifulsoup that scrapes a website with multiple pages by css selector
- Assistant
Sure, here's an example code to scrape a website with multiple pages using CSS selectors with the help of Beautiful Soup library in Python:
import requests from bs4 import BeautifulSoup # target website URL url = 'https://www.example.com/page' # headers (optional) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} # initial page number (optional) page = 1 while True: # make a request to the current page response = requests.get(url + str(page), headers=headers) soup = BeautifulSoup(response.content, 'html.parser') # scrape data using CSS selectors items = soup.select('div.item') for item in items: title = item.select_one('h2.title').text.strip() description = item.select_one('p.description').text.strip() link = item.select_one('a')['href'] print(f'{title}\n{description}\n{link}\n') # check if there's another page next_page = soup.select_one('a.next') if not next_page: break # update page number to the next page page += 1 - User
the website's multiple pages are links to an html page
- Assistant
In that case, you can modify the code to loop through a list of page URLs instead of iterating over a range of page numbers. Here's an example code to scrape a website with multiple linked pages using CSS selectors with the help of Beautiful Soup library in Python:
import requests from bs4 import BeautifulSoup # target website URLs urls = ['https://www.example.com/page1.html', 'https://www.example.com/page2.html', 'https://www.example.com/page3.html'] # headers (optional) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} for url in urls: # make a request to the current page response = requests.get(url, headers=headers) soup = BeautifulSoup(response.content, 'html.parser') # scrape data using CSS selectors items = soup.select('div.item') for item in items: title = item.select_one('h2.title').text.strip() description = item.select_one('p.description').text.strip() link = item.select_one('a')['href'] print(f'{title}\n{description}\n{link}\n')