Сравнение результатов BeautifulSoup - PullRequest
0 голосов
/ 07 марта 2019

Я покупаю дом и построил скребок BeautifulSoup, который работает как шарм - соскребая нужные мне метки с нашего местного сайта по недвижимости.Теперь мне просто нужно реализовать механизм, который будет уведомлять меня об изменениях на веб-сайте.

Мне нужно, чтобы он уведомлял меня, когда новый результат очистки будет отличаться от предыдущего - при изменении HTML.

previous_content = ''
URL = 'whatever.com'

while True:
    content = requests.get(URL)
    soup = BeautifulSoup(content.text, 'html.parser')
    titles = soup.find_all('span', attrs={'class':['title']})
    years = soup.find_all('span', attrs={'class':['year']})
    sizes = soup.find_all('span', attrs={'class':['size']})
    prices = soup.find_all('span', attrs={'class':['price']})

    for titles, years, sizes, prices in zip(titles, years, sizes, prices):
        print('Location: ' + titles.get_text(strip="True") + '\n' + 'Year: ' + years.get_text(strip="True"), '\n' + 'Size: ' + sizes.get_text(strip="True"), '\n' 'Price: ' + prices.get_text(strip="True"))
        previous_content = new_content
    if previous_content == new_content:
        print("CONTENT NOT CHANGED. | " + str(today))
    elif previous_content != new_content:
        print("CONTENT CHANGED | " + str(today))
    time.sleep(sleeptime)

Большое спасибо!

1 Ответ

0 голосов
/ 07 марта 2019

Я думаю, что вы допустили небольшую ошибку при назначении previous_content

Вы должны назначить previous_content в конце итерации, а не перед проверкой равенства с new_content, иначе оно всегда будет True

Что-то подобное должно работать (я не могу проверить)

previous_content = []
URL = 'whatever.com'

while True:
    content = requests.get(URL)
    soup = BeautifulSoup(content.text, 'html.parser')
    titles = soup.find_all('span', attrs={'class':['title']})
    years = soup.find_all('span', attrs={'class':['year']})
    sizes = soup.find_all('span', attrs={'class':['size']})
    prices = soup.find_all('span', attrs={'class':['price']})

    new_content = [] # Initialize the new_content list
    for titles, years, sizes, prices in zip(titles, years, sizes, prices):
        content = 'Location: ' + titles.get_text(strip="True") + '\n' + 'Year: ' + years.get_text(strip="True"), '\n' + 'Size: ' + sizes.get_text(strip="True"), '\n' 'Price: ' + prices.get_text(strip="True")
        print(content)
        new_content.append(content)
    if sorted(previous_content) == sorted(new_content): # The list needs to be sorted as I expect the order to change but not the content
        print("CONTENT NOT CHANGED. | " + str(today))
    else:
        print("CONTENT CHANGED | " + str(today))
    previous_content = new_content # Assigning for next iteration of the loop
    time.sleep(sleeptime)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...