Я хотел сделать небольшой проект в свободное время для практики и опыта и хотел написать веб-скребок для YUYU-TEI.jp. Я хотел создать веб-скребок для извлечения данных, встроенных в HTML-код страницы, и получения таких сведений о картах, как изображения, имена и цена.
Большую часть времени я использовал gpt и был искал способы очистки и выбрал beautifulsoup4. Мне удалось очистить данные с помощью локального хоста, но когда я развернул их на Heroku, я столкнулся со многими проблемами, одна из которых была «Ошибка клиента 403: запрещено для URL: https://yuyu-tei.jp/top/opc». .
большая часть моих проб и ошибок исходила из gpt, а также из других сообщений по этой теме, похожих на те, с которыми сталкивались другие.
Я пытался разместить заголовки, файлы cookie, прокси (которые были бесплатными, http:) и советы из других сообщений, но ничего из этого не сработало. Похоже, что все они были заблокированы веб-сайтом, независимо от того, какие параметры я указал. Ниже приведен код, который я написал для своего приложения Flask, развернутого на Heroku:
from flask import Flask, jsonify, request
import requests
from bs4 import BeautifulSoup
from googletrans import Translator
import os
app = Flask(__name__)
# Define a route for scraping cards
@app.route('/scrape_cards')
def scrape_cards():
url = request.args.get('url') # Get the URL from the query parameter
translator = Translator()
cards = []
if not url:
return jsonify({"error": "No URL provided"}), 400 # Bad Request if URL is missing
headers = {
'User-Agent': 'Mozilla/6.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
'Accept-Language': 'ja-JP,ja;q=0.9',
'Referer': 'https://yuyu-tei.jp/',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cookie': 'XSRF-TOKEN=###my token#'
}
# Get proxy settings from environment variables
proxy_user = os.getenv('###my info###')
proxy_pass = os.getenv('###my info###')
proxy_host = os.getenv('###my info###')
proxies = {
'http': f'http://{proxy_user}:{proxy_pass}@{proxy_host}',
}
try:
response = requests.get(url, headers=headers, proxies=proxies)
response.raise_for_status() # This will raise an HTTPError for bad responses (4xx or 5xx)
soup = BeautifulSoup(response.text, 'html.parser')
card_sections = soup.find_all('div', class_='py-4 cards-list')
for section in card_sections:
category_element = section.find('h3', class_='text-primary fs-4 shadow fw-bold')
category_name = category_element.find('span').get_text(strip=True) if category_element else 'Category not found'
card_elements = section.find_all('div', class_='card-product')
for card in card_elements:
name_element = card.find('h4', class_='text-primary fw-bold')
name_japanese = name_element.get_text(strip=True) if name_element else 'Name not found'
# Handle translation within try-except to catch potential issues with the Translator
try:
name_english = translator.translate(name_japanese, src='ja', dest='en').text
except Exception as e:
name_english = 'Translation error: ' + str(e)
price_element = card.find('strong')
price_text = price_element.get_text(strip=True) if price_element else 'Price not found'
img_element = card.find('img', class_='card img-fluid')
img_src = img_element['src'] if img_element and 'src' in img_element.attrs else 'Image not found'
card_number_element = card.find('span', class_='d-block border border-dark p-1 w-100 text-center my-2')
card_number = card_number_element.get_text(strip=True) if card_number_element else 'Card number not found'
cards.append({
'name_japanese': name_japanese,
'name_english': name_english,
'price': price_text,
'image_link': img_src,
'card_number': card_number,
'category': category_name
})
return jsonify(cards)
except requests.exceptions.HTTPError as http_err:
return jsonify({"error": f"HTTP error occurred: {http_err}"}), 500
except Exception as e:
return jsonify({"error": f"An error occurred: {str(e)}"}), 500
@app.route('/getsets')
def getsets():
url = 'https://yuyu-tei.jp/top/opc'
headers = {
'User-Agent': 'Mozilla/6.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
'Accept-Language': 'ja-JP,ja;q=0.9',
'Referer': 'https://yuyu-tei.jp/',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cookie': 'XSRF-TOKEN=###my info###'
}
# Get proxy settings from environment variables
proxy_user = os.getenv('###my info###')
proxy_pass = os.getenv('###my info###')
proxy_host = os.getenv('###my info###')
proxies = {
'http': f'http://{proxy_user}:{proxy_pass}@{proxy_host}',
}
try:
# Include the headers in the request
response = requests.get(url, headers=headers, proxies=proxies)
response.raise_for_status() # Raise an error for bad responses
soup = BeautifulSoup(response.text, 'html.parser')
booster_div = soup.find('div', id='side-sell-target-12')
if booster_div:
buttons = booster_div.find_all('button')
sets = []
for button in buttons:
button_url = button['onclick'].split("'")[1]
set_name = button.get_text(strip=True)
sets.append({'name': set_name, 'url': button_url})
return jsonify(sets)
else:
return jsonify({"error": "Booster div not found"}), 404
except requests.exceptions.RequestException as e:
return jsonify({"error": f"Failed to retrieve the page: {str(e)}"}), 500
if __name__ == "__main__":
app.run()
Подробнее здесь: https://stackoverflow.com/questions/791 ... -on-heroku
Столкнулся с проблемой при развертывании веб-скребка на Heroku. ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как исключить классы div «modal-content» и «modal-body» из веб-скребка Pyppeteer?
Anonymous » » в форуме Python - 0 Ответы
- 28 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как автоматически заполнить CAPTCHA изображением с помощью веб-скребка в ASP.NET C#? [закрыто]
Anonymous » » в форуме C# - 0 Ответы
- 7 Просмотры
-
Последнее сообщение Anonymous
-