Below is a portion of the code i have written to scrape the bikesales.com.au website for details of bikes for sales (The full code is here). This finds all the 'href' attributes on each search page and tries to request the html for each href corresponding to each bike for sale. My code works correctly, however I had to add some retry attempts with exponential backoff to avoid the following error:
ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)
The code works correctly, however I would like to avoid the backoff approach if possible.
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
def get_html_content(url, multiplier=1):
"""
Retrieve the contents of the url.
"""
# Be a responisble scraper.
# The multiplier is used to exponentially increase the delay when there are several attempts at connecting to the url
time.sleep(2*multiplier)
# Get the html from the url
try:
with closing(get(url)) as resp:
content_type = resp.headers['Content-Type'].lower()
if is_good_response(resp):
return resp.content
else:
# Unable to get the url response
return None
except RequestException as e:
print("Error during requests to {0} : {1}".format(url, str(e)))
if __name__ == '__main__':
baseUrl = 'https://www.bikesales.com.au/'
url = 'https://www.bikesales.com.au/bikes/?q=Service%3D%5BBikesales%5D'
content = get_html_content(url)
html = BeautifulSoup(content, 'html.parser')
BikeList = html.findAll("a", {"class": "item-link-container"})
# Cycle through the list of bikes on each search page.
for bike in BikeList:
# Get the URL for each bike.
individualBikeURL = bike.attrs['href']
BikeContent = get_html_content(baseUrl+individualBikeURL)
# Reset the miltipler for each new url
multiplier = 1
## occasionally the connection is lost, so try again.
## Im not sure why the connection is lost, i might be that the site is trying to guard against scraping software.
# If initial attempt to connect to the url was unsuccessful, try again with an increasing delay
while (BikeContent == None):
# Limit the exponential delay to 16x
if (multiplier < 16):
multiplier *= 2
BikeContent = get_html_content(baseUrl+individualBikeURL,multiplier)
My question is, Is there something that i am missing in the implementation of the request? or, is this just a result of the site denying scraping tools?
is_good_response
? \$\endgroup\$