Очистить веб-сайты с уникальным URL (python) - PullRequest
0 голосов
/ 31 марта 2020

В настоящее время я работаю над проектом очистки веб-страниц, но у меня возникают трудности с URL-адресом веб-сайта, поскольку он не меняется при просмотре страниц.

Веб-сайт: https://www.centris.ca/fr/triplex~a-vendre~montreal-mercier-hochelaga-maisonneuve?uc=1&view=Thumbnail

Моя цель - очистить все здания на двух страницах.

Единственный способ очистить данные - использовать инструмент проверки и скопировать оболочку все объявления.

Это мой код:

from bs4 import BeautifulSoup
import requests
import csv
import string
import glob

#Grab the soup (content)
source = requests.get("https://www.centris.ca/fr/triplex~a-vendre~montreal-mercier-hochelaga-maisonneuve?uc=1&view=Thumbnail")

soup = BeautifulSoup(source.content, 'html.parser')

    #Loop through all the ads on the page
    for ad in soup.find_all('div', {"data-id":"templateThumbnailItem"}):
        if (soup.find('div', {"class":"price"})):

            #Get the address
            address = ad.find('span', {"class":"address"})
            address = address.findChild().text
            address = address.strip()


            #Get the district
            district = ad.find('span', {"class":"address"})
            district = district.findChildren()[1].text
            district = district.strip()


            #Get the type
            typeBuilding = ad.find('span', {"class":"category"}).text
            typeBuilding = typeBuilding.strip()
            typeBuilding = typeBuilding[0:7].strip()


            #Get the Price
            price = ad.find('span', {"itemprop":"price"}).text
            price = price.replace('$','')
            price = price.replace(u'\xa0','')
            price = int(str(price))

            cnt = cnt + 1


            print(f'Adresse: {address}, Quartier: {district}, Type: {typeBuilding}, Prix: {price}$')

Спасибо за помощь!

1 Ответ

0 голосов
/ 31 марта 2020
import requests
from bs4 import BeautifulSoup
import csv


def main(url):
    with requests.Session() as req:
        r = req.get(
            "https://www.centris.ca/fr/triplex~a-vendre~montreal-mercier-hochelaga-maisonneuve?uc=1&view=Thumbnail")
        with open("data.csv", 'w', newline="", encoding="UTF-8") as f:
            writer = csv.writer(f)
            writer.writerow(["Address", "Quartier", "Type", "Price"])
            for num in range(0, 40, 20):
                data = {'startPosition': num}
                r = req.post(url, json=data).json()
                html = r["d"]["Result"]["html"]
                soup = BeautifulSoup(html, 'html.parser')
                prices = [format(int(price.get("content")), ',d') for price in soup.findAll(
                    "span", itemprop="price")]
                block = soup.findAll("div", class_="location-container")
                ty = [ty.div.get_text(strip=True) for ty in block]
                add = [add.select_one(
                    "span.address div").text for add in block]
                quartier = [quar.select_one(
                    "span.address div:nth-child(2)").text for quar in block]
                final = zip(add, quartier, ty, prices)
                writer.writerows(final)


main("https://www.centris.ca/Mvc/Property/GetInscriptions")

Вывод: Просмотр онлайн

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...