'Handling this website which is redirecting to the same url with BeautifulSoup

So I'm scrapping this website: https://www.hepsiburada.com/apple-macbook-pro-m1-cip-8gb-256gb-ssd-macos-13-qhd-tasinabilir-bilgisayar-uzay-grisi-myd82tu-a-p-HBV0000130VNO-yorumlari

I'm scraping all the reviews for a particular product on this website. Also handling the pagination. The URL for different pages is like:

https://www.hepsiburada.com/apple-macbook-pro-m1-cip-8gb-256gb-ssd-macos-13-qhd-tasinabilir-bilgisayar-uzay-grisi-myd82tu-a-p-HBV0000130VNO-yorumlari?sayfa=1

https://www.hepsiburada.com/apple-macbook-pro-m1-cip-8gb-256gb-ssd-macos-13-qhd-tasinabilir-bilgisayar-uzay-grisi-myd82tu-a-p-HBV0000130VNO-yorumlari?sayfa=2

https://www.hepsiburada.com/apple-macbook-pro-m1-cip-8gb-256gb-ssd-macos-13-qhd-tasinabilir-bilgisayar-uzay-grisi-myd82tu-a-p-HBV0000130VNO-yorumlari?sayfa=3

The code is working as expected but when accessing the (n/2)+1 page, the website is redirecting to the first page of the comments. That is suppose total pages for a website is 12. Upon accessing the 7th page directly for which the URL is https://www.hepsiburada.com/apple-macbook-pro-m1-cip-8gb-256gb-ssd-macos-13-qhd-tasinabilir-bilgisayar-uzay-grisi-myd82tu-a-p-HBV0000130VNO-yorumlari?sayfa=7
It redirects to the first page for which the URL is https://www.hepsiburada.com/apple-macbook-pro-m1-cip-8gb-256gb-ssd-macos-13-qhd-tasinabilir-bilgisayar-uzay-grisi-myd82tu-a-p-HBV0000130VNO-yorumlari

When we goto the 7th page using the website's page links, it opens the 7th page with no issues. But its only when we access the page directly, its redirecting.

How can I handle this with BeautifulSoup? Also, Please don't suggest using Selenium as client needs the task to be done using BeautifulSoup only.

Here's the Python code:

from urllib import response
from bs4 import BeautifulSoup
from django.shortcuts import redirect
import requests
import sys
import re

file_path = 'output.txt'
sys.stdout = open(file_path, "w", encoding="utf-8")

# url = sys.argv[1]
url = 'https://www.hepsiburada.com/apple-macbook-pro-m1-cip-8gb-256gb-ssd-macos-13-qhd-tasinabilir-bilgisayar-uzay-grisi-myd82tu-a-p-HBV0000130VNO-yorumlari'

response = requests.get(url, headers={"User-Agent":"Mozilla/5.0"})

soup = BeautifulSoup(response.content, 'html5lib')
div = soup.find_all('div', class_='paginationContentHolder')
# l = [(div.contents[0].strip(), span.text.strip())
#     for div in soup.select('div.league-data')
#     for span in div.select('span')] 

divlist = soup.find_all("div", {'itemprop':'review'})
# print(divlist)
# for i in divlist:
#     print(i)
#     print('---------------------------')

pagecount = soup.find('div', {'class':'paginationBarHolder'})
pagelist = pagecount.find_all('ul')
pagelistnew = []
for i in pagelist[0]:
    if i.text.isdigit():
        pagelistnew.append(int(i.text))

maxpage = max(pagelistnew)
print(maxpage)

firstcard = divlist[0]
for i in divlist:
    if i.find('span', {'itemprop':'description'}):
        print('Review: ' + i.find('span', {'itemprop':'description'}).text)
    
    ratinglist = i.find_all('div', {'class':'star', 'style':'width:12px;height:12px'})
    print('Rating: ' + str(len(ratinglist)))
    print('Date: ' + i.find('span', {'itemprop': 'datePublished'}).text)
    
    # rating = 0
    # for j in ratinglist:
    #     rating = rating + 1
    # print(rating)
    
    print()

urlnew = 'https://www.hepsiburada.com/apple-macbook-pro-m1-cip-8gb-256gb-ssd-macos-13-qhd-tasinabilir-bilgisayar-uzay-grisi-myd82tu-a-p-HBV0000130VNO-yorumlari?sayfa='

for i in range(2, maxpage + 1): 
    # payload = {'sayfa':i}
    req = requests.get(urlnew + str(i), headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246", 'Access-Control-Allow-Origin': '*'}, allow_redirects=False)
    print('URL: ' + urlnew + str(i))
    print(req.status_code)
    print()
    soup2 = BeautifulSoup(req.content, 'html5lib')
    divlist1 = soup2.find_all("div", {'itemprop':'review'})

    # firstcard1 = divlist1[0]
    for l in divlist1:
        if l.find('span', {'itemprop':'description'}):
            print('Review: ' + l.find('span', {'itemprop':'description'}).text)
        
        ratinglist1 = l.find_all('div', {'class':'star', 'style':'width:12px;height:12px'})
        print('Rating: ' + str(len(ratinglist1)))
        print('Date: ' + l.find('span', {'itemprop': 'datePublished'}).text)
        
        print()


Solution 1:[1]

To get all reviews you can use their API url. For example:

import json
import requests


# HBV0000130VNO is from the URL in the question
url = "https://user-content-gw-hermes.hepsiburada.com/queryapi/v2/ApprovedUserContents?skuList=HBV0000130VNO&from={}&size=10"

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0"
}

from_ = 0
while True:
    data = requests.get(url.format(from_), headers=headers).json()

    # uncomment to see all data:
    # print(json.dumps(data, indent=4))

    for d in data["data"]["approvedUserContent"]["approvedUserContentList"]:
        print(d["customer"]["name"], d["customer"]["surname"])
        print(d["review"]["content"])
        print()

    if data["currentItemCount"] != 10:
        break

    from_ += 10

Prints:

h********** z*********
Mükemmel kalitede bir ürün

A*** T*****
tek kelimeyle EFSANE. Her zaman oldu?u gibi Apple kalitesi 1 numara. Benim kullan?m?mla 2 gün gidiyor ?arj? günlük i? maillerimi yan?tl?yor raporlar?m? inceliyorum. Ak?amda belki bir dizi-film aç?p ?arj?n? bitiriyorum. Performansa diyecek hiç bir ?ey yok. Bu mimari ve altyap? son derece muazzam çal??acak ?ekilde tasarlanm?? zaten.

E*** D*******
Kesinlikle fiyat?yla performans?n?n birbirini fazlas?yla kar??lad??? ?ahane bir i? istasyonu. Malzeme yap?s? ve içindeki yeni M1 Yonga seti i?lemcisi ile uzun süreli kullan?m? ve i? gücünü vaat ediyor. Ayr?ca içinden ç?kan 61W'l?k Adaptörü ile h?zl? ?arj olmas? ayr? bir güzelli?i. Hepsiburada'ya ve Lojisti?i olan HepsiJet'e h?zl? ve güvenilir olduklar? için çok te?ekkür ederim.

O**** B****
Mükemmel bir ürün. Kullanmadan önce bu ekosisteme kar?? yarg?lar? olanlar, ?imdi macbook'uma tap?yorlar.

A**** A*********
2019 macbook airden geçi? yapt???m için söyleyebilirim ki özellikle Apple'?n m1 çip için optimize etti?i safari süper h?zl? çal???yor chrome kullanmay? b?rakt?m diyebilirim görüntü ses kalitesi çok daha iyi ve i?lemci çok h?zl? çok memnunum pil 20 saat gidiyormu? ben genelde güç kayna??na ba?l? kullan?yorum

Y**** G*****
Ben sat?n ald???mda MBA 512 GB ve MBP 256 fiyatlar? birbirine çok yak?nd?. O yüzden MBP tercih ettim. Arada oyun oynamak isteyenler için MBA yerine kesinlikle tecih edilmesi gereken ürün. Çünkü baz? oyunlarda throttling problemi ya?anabiliyor (Tomb Raider oyunlar? gibi)

?***** a****
Tek kelimeyle Apple kalitesiyle tasarlanm?? ?ahane bir ürün; fakat Türkiye ?artlar?ndan dolay? s?rt?m?za a??r yükler bindiren kur fark?ndan kaynaklanan kallavi fiyat? biraz üzüyor.


...and so on.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrej Kesely