Не работает парсер на питоне
Не работает парсер, не понимаю в чем проблема, все раньше нормально работало, а сейчас ошибку выдает:
Traceback (most recent call last):
File "123.py", line 36, in <module>
parse()
File "123.py", line 30, in parse
img = get_image(html)
File "123.py", line 16, in get_image
soup = BeautifulSoup(html, 'html.parser')
File "C:\Users\musix\AppData\Local\Programs\Python\Python38\lib\site-packages\bs4\__init__.py", line 307, in __init__
elif len(markup) <= 256 and (
TypeError: object of type 'Response' has no len()
Вот сам код:
import requests
from bs4 import BeautifulSoup
import csv
import os
URL = 'https://ptk-svarka.ru/catalog/apparaty-poluavtomaticheskoy-svarki-mig'
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36', 'accept': '*/*'}
FILE = 'svarka.csv'
def get_html(url, params=None):
r = requests.get(url, headers=HEADERS, params=params)
return r
def get_image(html):
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='b-products')
image = []
for img in image:
image.append(
item.find('a', class_='b-products__text').get('href')
)
return image
def parse():
URL = input('Введите URL: ')
URL = URL.strip()
html = get_html(URL)
if html.status_code == 200:
img = get_image(html)
print(img)
else:
print('Error')
parse()
Ответы (1 шт):
Автор решения: gil9red
→ Ссылка
В BeautifulSoup нужно передавать строку, байты или файловый объект, а вы передали объект requests.Response.
Советую давать правильные имена параметрам и указывать тип параметров и возвращаемых значений в функциях, это не обяжет интерпретатор проверять типы, но поможет IDE и программистам.
Пример:
...
def get_html(url, params=None) -> requests.Response: # <<<<<
r = requests.get(url, headers=HEADERS, params=params)
return r
def get_image(html: bytes): # <<<<<
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='b-products')
image = []
for img in image:
image.append(
item.find('a', class_='b-products__text').get('href')
)
return image
def parse():
URL = input('Введите URL: ')
URL = URL.strip()
rs = get_html(URL) # <<<<<
if rs.status_code == 200: # <<<<<
img = get_image(rs.content) # <<<<<
print(img)
else:
print('Error')