Я написал этот код для анализа информации с веб-страницы в текстовый файл. Он работает нормально, но может записать в текстовый файл только 501 строку. Как я могу исправить код, чтобы убрать это ограничение?
import requests
from bs4 import BeautifulSoup
import re
brand = input(print("brand: "))
if brand == 0:
brand = None
limit = int(input(print('limit: ')))`
URL = f"URL" #URL of the web page with {brand - number in the url} and {limit - max found results}
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
def parse_forms():#parses specific forms which contain needed information
try:
response = requests.get(URL, headers=HEADERS, timeout=15)
response.raise_for_status()
except requests.RequestException as e:
print("Request failed:", e)
return []
soup = BeautifulSoup(response.text, "html.parser")
forms = soup.find_all("form")#in my webpage they use to organize the elements of the page so i find information by this tag
car_list = []
for form in forms:
car_data = {}
# --- Extract hidden input values (often contain lot ID etc.)
hidden_inputs = form.find_all("input", type="hidden")
for inp in hidden_inputs:
name = inp.get("name")
value = inp.get("value")
if name and value:
car_data[name] = value
else:
car_data[name] = "None"
car_list.append(car_data)
return car_list
if __name__ == "__main__":
cars = parse_forms()
cars = cars[1:]#this operation removes unwanted infomation
file_name = ""
if int(brand) == 0:
file_name = "car_list"
else:
file_name = car_sep[0]#first word of the array is always the brand
output = open(f'{file_name}.txt', 'w', encoding="utf-8")
output.write("Brand Model Year Body StartPrice Mileage IMG1 IMG2")
output.write("\n")
output.close()
print(f"\nFound {len(cars)} form entries\n")
car_sep = []
for car in cars[:len(cars)-1]:
car_sep.append(car['tomylistMARKA_NAME'])
car_sep.append(car['tomylistMODEL_NAME'])
car_sep.append(car['tomylistYEAR'])
car_sep.append(car['tomylistKUZOV'])
car_sep.append(car['tomylistSTART'])
car_sep.append(car['tomylistMILEAGE'])
car_sep.append(car['tomylistIMAGES'])
car_sep.append(car['tomylistIMAGES2[]'])
car_sep = ['_'.join(item.split(" ")) for item in car_sep]#i replace all the spaces with "_" to prepare for the future data editing
output = open(f'{file_name}.txt', 'a', encoding="utf-8")
for i in range (0, len(car_sep)):
output.write(str(car_sep))
output.write(" ")
output.write('\n')
output.close()
car_sep.clear()
print(f"\nFound {len(cars)} form entries\n")#just to check how much information i have got from the page (idk why but this number deosn't exceed 501)
Подробнее здесь: https://stackoverflow.com/questions/798 ... of-my-code
Как исправить ограничение на количество строк в моем коде? ⇐ Python
Программы на Python
-
Anonymous
1772807369
Anonymous
Я написал этот код для анализа информации с веб-страницы в текстовый файл. Он работает нормально, но может записать в текстовый файл только 501 строку. Как я могу исправить код, чтобы убрать это ограничение?
import requests
from bs4 import BeautifulSoup
import re
brand = input(print("brand: "))
if brand == 0:
brand = None
limit = int(input(print('limit: ')))`
URL = f"URL" #URL of the web page with {brand - number in the url} and {limit - max found results}
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
def parse_forms():#parses specific forms which contain needed information
try:
response = requests.get(URL, headers=HEADERS, timeout=15)
response.raise_for_status()
except requests.RequestException as e:
print("Request failed:", e)
return []
soup = BeautifulSoup(response.text, "html.parser")
forms = soup.find_all("form")#in my webpage they use to organize the elements of the page so i find information by this tag
car_list = []
for form in forms:
car_data = {}
# --- Extract hidden input values (often contain lot ID etc.)
hidden_inputs = form.find_all("input", type="hidden")
for inp in hidden_inputs:
name = inp.get("name")
value = inp.get("value")
if name and value:
car_data[name] = value
else:
car_data[name] = "None"
car_list.append(car_data)
return car_list
if __name__ == "__main__":
cars = parse_forms()
cars = cars[1:]#this operation removes unwanted infomation
file_name = ""
if int(brand) == 0:
file_name = "car_list"
else:
file_name = car_sep[0]#first word of the array is always the brand
output = open(f'{file_name}.txt', 'w', encoding="utf-8")
output.write("Brand Model Year Body StartPrice Mileage IMG1 IMG2")
output.write("\n")
output.close()
print(f"\nFound {len(cars)} form entries\n")
car_sep = []
for car in cars[:len(cars)-1]:
car_sep.append(car['tomylistMARKA_NAME'])
car_sep.append(car['tomylistMODEL_NAME'])
car_sep.append(car['tomylistYEAR'])
car_sep.append(car['tomylistKUZOV'])
car_sep.append(car['tomylistSTART'])
car_sep.append(car['tomylistMILEAGE'])
car_sep.append(car['tomylistIMAGES'])
car_sep.append(car['tomylistIMAGES2[]'])
car_sep = ['_'.join(item.split(" ")) for item in car_sep]#i replace all the spaces with "_" to prepare for the future data editing
output = open(f'{file_name}.txt', 'a', encoding="utf-8")
for i in range (0, len(car_sep)):
output.write(str(car_sep[i]))
output.write(" ")
output.write('\n')
output.close()
car_sep.clear()
print(f"\nFound {len(cars)} form entries\n")#just to check how much information i have got from the page (idk why but this number deosn't exceed 501)
Подробнее здесь: [url]https://stackoverflow.com/questions/79898566/how-do-i-fix-the-string-limit-of-my-code[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия