Я создавал приложение для извлечения цен с веб-сайта, посвященного аренде комнат, и их усреднения, чтобы помочь новичкам.
Однако вся работа сделана, в настоящее время код очищает только одну страницу, которую я ему дал, я пытаюсь заставить его очистить следующую страницу и так далее, пока не появятся все доступные цены.
Я дошел до того момента, когда он будет очищать один URL-адрес, который я ему даю, и следующий, и теперь я просто пытаюсь заставить его повторить функцию, которая заставляет его проходить один раз, пока не будет » следующая »страница для перехода.
Однако когда я пытаюсь отформатировать свой код таким образом, чтобы я мог легко повторить его, используя оператор if и функции, я начинаю получать много «unresolved reference«,»shadows name from outer scope«, а также «local variable value not used«ошибки.
Я опубликую сценарий, который работает (версия, которая очищает только страницу, которую я ей даю, и еще одну), а затем сценарий, отформатированный по-другому, в попытке легко повторить определенную функцию.
Моя IDE — это Pycharm, и я использую язык Python с модулем beautifulsoup для очистки.
Скрипт, который работает, но очищает только одну страницу (я знаю почему):
from bs4 import BeautifulSoup
import requests
def getting_the_prices():
global prices
html_address = input("Insert page address:")
html_text = requests.get(html_address).text
soup = BeautifulSoup(html_text, 'lxml')
prices = soup.find_all('strong', class_='listingPrice')
next_page_button_finder = soup.find('ul', class_='navnext').findAll('li')[-1].text
if next_page_button_finder == "Next >>":
next_page_address_finder = soup.find('ul', class_='navnext').findAll('li')[-1].find('a')['href']
html_link_numbers_list = []
for word in html_address.split():
if word.isdigit():
html_link_numbers_list.append(int(word))
html_link_numbers_string = "".join(map(str, html_link_numbers_list))
html_address = html_address.replace("?search_id=", "")
html_address = html_address.replace("&", "")
html_address = html_address.replace(html_link_numbers_string, "")
next_page_address = html_address + next_page_address_finder
next_page_text = requests.get(next_page_address).text
next_page_soup = BeautifulSoup(next_page_text, 'lxml')
next_page_prices = next_page_soup.find_all('strong', class_='listingPrice')
prices = prices + next_page_prices
# This would be where it loops, however, I could not loop in this script, and thus
# tried to seperate this script into two pieces with functions as you will see in the
# following script.
refining_the_prices()
else:
refining_the_prices()
А вот сценарий со всеми ошибками:
from bs4 import BeautifulSoup
import requests
def getting_the_prices():
global prices
global soup
global html_address
html_address = input("Insert page address:")
html_text = requests.get(html_address).text
soup = BeautifulSoup(html_text, 'lxml')
prices = soup.find_all('strong', class_='listingPrice')
def checking_for_another_page():
next_page_button_finder = soup.find('ul', class_='navnext').findAll('li')[-1].text
if next_page_button_finder == "Next >>":
next_page_address_finder = soup.find('ul', class_='navnext').findAll('li')[-1].find('a')['href']
html_link_numbers_list = []
for word in html_address.split():
if word.isdigit():
html_link_numbers_list.append(int(word))
html_link_numbers_string = "".join(map(str, html_link_numbers_list))
html_address = html_address.replace("?search_id=", "")
html_address = html_address.replace("&", "")
html_address = html_address.replace(html_link_numbers_string, "")
next_page_address = html_address + next_page_address_finder
next_page_text = requests.get(next_page_address).text
next_page_soup = BeautifulSoup(next_page_text, 'lxml')
next_page_prices = next_page_soup.find_all('strong', class_='listingPrice')
prices = prices + next_page_prices
checking_for_another_page()
else:
refining_the_prices()
Я также пробовал переехать:
html_link_numbers_list = []
for word in html_address.split():
if word.isdigit():
html_link_numbers_list.append(int(word))
html_link_numbers_string = "".join(map(str, html_link_numbers_list))
html_address = html_address.replace("?search_id=", "")
html_address = html_address.replace("&", "")
html_address = html_address.replace(html_link_numbers_string, "")
checking_for_another_page()
Вплоть до def getting_the_prices() но тогда программа просто не работает.
Я также пробовал переименовать «prices«переменная в»prices = prices + next_page_prices» к «new_prices«и снова в refining_the_prices функция, но безрезультатно.
Я также пытался изолировать эту часть кода в собственной функции, но снова получаю ошибки.
Я также пробовал сверхбрутто-маршрут, как будто мой код еще не был достаточно грубым, просто повторял операторы if внутри операторов if в первом скрипте, но это тоже не работает.
Я действительно застрял здесь, поэтому любая помощь будет принята с благодарностью.
Вот остальная часть кода, если это необходимо, однако, кроме этого, нет более полезной информации, кроме этого. Весь код за двумя приведенными выше сценариями идентичен в обоих сценариях:
from bs4 import BeautifulSoup
import requests
def getting_the_prices():
global prices
global soup
global html_address
html_address = input("Insert page address:")
html_text = requests.get(html_address).text
soup = BeautifulSoup(html_text, 'lxml')
prices = soup.find_all('strong', class_='listingPrice')
def checking_for_another_page():
next_page_button_finder = soup.find('ul', class_='navnext').findAll('li')[-1].text
if next_page_button_finder == "Next >>":
next_page_address_finder = soup.find('ul', class_='navnext').findAll('li')[-1].find('a')['href']
html_link_numbers_list = []
for word in html_address.split():
if word.isdigit():
html_link_numbers_list.append(int(word))
html_link_numbers_string = "".join(map(str, html_link_numbers_list))
html_address = html_address.replace("?search_id=", "")
html_address = html_address.replace("&", "")
html_address = html_address.replace(html_link_numbers_string, "")
next_page_address = html_address + next_page_address_finder
next_page_text = requests.get(next_page_address).text
next_page_soup = BeautifulSoup(next_page_text, 'lxml')
next_page_prices = next_page_soup.find_all('strong', class_='listingPrice')
prices = prices + next_page_prices
checking_for_another_page()
else:
refining_the_prices()
def refining_the_prices():
global no_pound
prices_string = str(prices)
pound_punctuation = '£-<=">/!'
no_pound = ""
for char in prices_string:
if char not in pound_punctuation:
no_pound = no_pound + char
no_pound = no_pound.replace("a", " ")
extracting_the_numbers()
def extracting_the_numbers():
global numbers
numbers = []
for word in no_pound.split():
if word.isdigit():
numbers.append(int(word))
averaging_the_numbers()
def averaging_the_numbers():
average = sum(numbers)/len(numbers)
print(average)
getting_the_prices()
getting_the_prices()
![Я изо всех сил пытаюсь понять, почему этот сценарий работает, а другой нет. [closed] TheFAQ.ru](https://thefaq.ru/wp-content/uploads/2023/01/logo-250.png)