I am using https://www.realtor.com/realestateagents/phoenix_az//pg-2 as my starting point. I want to go from page 2 to page 5 and each page in-between while collecting names and numbers. I am collecting information on page 2 perfectly however I can not get it to go to the next page without having to plug in a new url. I am trying to set up a loop to do this automatically however after coding what I thought would be a loop im just getting the information only on page 2 (the starting point) before the scraper stops. I am new too loops and have tried multiple ways but can get none to work.
Below is the complete code for now.
import requests
from requests import get
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import numpy as np
from numpy import arange
import pandas as pd
from time import sleep
from random import randint
headers = {'user-agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5)'
'AppleWebKit/537.36 (KHTML, like Gecko)'
'Chrome/45.0.2454.101 Safari/537.36'),
'referer': 'https://www.realtor.com/realestateagents/phoenix_az//pg-2'}
my_url = 'https://www.realtor.com/realestateagents/phoenix_az//pg-2'
#opening up connection, grabbing the page
uClient = uReq(my_url)
#read page
page_html = uClient.read()
#close page
uClient.close()
pages = np.arange(2, 3, 1)
for page in pages:
page = requests.get("https://www.realtor.com/realestateagents/phoenix_az//pg-" , headers=headers)
#html parsing
page_soup = soup(page_html, "html.parser")
#finds all realtors on page
containers = page_soup.findAll("div",{"class":"agent-list-card clearfix"})
#creating csv file
filename = "phoenix.csv"
f = open(filename, "w")
headers = "agent_name, agent_number\n"
f.write(headers)
#controlling scrape speed
for container in containers:
try:
name = container.find('div', class_='agent-name text-bold')
agent_name = name.a.text.strip()
except AttributeError:
print("-")
try:
number = container.find('div', class_='agent-phone hidden-xs hidden-xxs')
agent_number = number.text.strip()
except AttributeError:
print("-")
except NameError:
print("-")
try:
print("name: " + agent_name)
print("number: " + agent_number)
except NameError:
print("-")
try:
f.write(agent_name + "," + agent_number + "\n")
except NameError:
print("-")
f.close()