내 연락처 정보
우편메소피아@프로톤메일.com
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
다년간의 크롤러 업계 경험으로 인해 다양한 수요 코드를 프로그래밍하는 것은 정말 힘들고 세심한 작업입니다. AI의 인기로 AI 자동화를 통해 원하는 텍스트 콘텐츠를 자동으로 캡처하고 생성하는 것이 가능한지 고민하고 있습니다. 프로그램들. . 크롤러 기술(스크래피 등)과 생성 AI 모델(GPT-4 등)을 결합해 완성한다는 게 전제다.
다음은 AIGC 크롤러 클래스에 대한 내 생각으로, AIGC 크롤러 애플리케이션을 구축하는 방법을 보여줍니다.
1. 필요한 종속성 설치
먼저 Scrapy와 OpenAI의 API 클라이언트 라이브러리가 설치되어 있는지 확인하세요.
pip install scrapy openai
2. OpenAI API 구성
OpenAI API 키가 있어야 하고 환경 변수를 구성하거나 코드에서 직접 사용해야 합니다.
3. Scrapy 크롤러 생성
다음은 콘텐츠를 스크랩하고 새 콘텐츠를 생성하는 기본 Scrapy 크롤러의 예입니다.
my_spider.py
import scrapy
import openai
class AIGCSpider(scrapy.Spider):
name = 'aigc_spider'
start_urls = ['http://example.com']
def __init__(self, *args, **kwargs):
super(AIGCSpider, self).__init__(*args, **kwargs)
openai.api_key = 'your-openai-api-key' # 替换为你的OpenAI API密钥
def parse(self, response):
# 提取网页内容
content = response.xpath('//body//text()').getall()
content = ' '.join(content).strip()
# 使用OpenAI生成新内容
generated_content = self.generate_content(content)
# 处理生成的内容,如保存到文件
with open('generated_content.txt', 'a') as f:
f.write(generated_content + 'n')
self.log(f"Generated content for {response.url}")
def generate_content(self, prompt):
try:
response = openai.Completion.create(
engine="davinci-codex",
prompt=prompt,
max_tokens=150
)
generated_text = response.choices[0].text.strip()
return generated_text
except Exception as e:
self.log(f"Error generating content: {e}")
return ""
4. Scrapy 프로젝트 구성
반드시settings.py
USER_AGENT 및 다운로드 지연과 같은 적절한 설정을 구성합니다.
settings.py
BOT_NAME = 'aigc_bot'
SPIDER_MODULES = ['aigc_bot.spiders']
NEWSPIDER_MODULE = 'aigc_bot.spiders'
# 遵守robots.txt规则
ROBOTSTXT_OBEY = True
# 用户代理
USER_AGENT = 'aigc_bot (+http://www.yourdomain.com)'
# 下载延迟
DOWNLOAD_DELAY = 1
5. 크롤러 실행
명령줄을 통해 Scrapy 크롤러를 실행합니다.
scrapy crawl aigc_spider
6. 확장된 기능
여러 페이지 처리
개정하다parse
메서드를 사용하면 여러 페이지를 처리하고 심층적인 크롤링을 수행할 수 있습니다.
def parse(self, response):
# 提取网页内容
content = response.xpath('//body//text()').getall()
content = ' '.join(content).strip()
# 使用OpenAI生成新内容
generated_content = self.generate_content(content)
# 处理生成的内容,如保存到文件
with open('generated_content.txt', 'a') as f:
f.write(f"URL: {response.url}n")
f.write(generated_content + 'nn')
self.log(f"Generated content for {response.url}")
# 跟踪所有链接
for href in response.css('a::attr(href)').get():
yield response.follow(href, self.parse)
더 많은 빌드 설정 추가
추가 등 생성된 콘텐츠의 매개변수를 조정합니다.temperature
그리고top_p
더욱 다양한 콘텐츠를 생성하기 위한 매개변수입니다.
def generate_content(self, prompt):
try:
response = openai.Completion.create(
engine="davinci-codex",
prompt=prompt,
max_tokens=150,
temperature=0.7,
top_p=0.9
)
generated_text = response.choices[0].text.strip()
return generated_text
except Exception as e:
self.log(f"Error generating content: {e}")
return ""
위 내용은 Scrapy와 OpenAI API를 결합하여 웹 사이트 콘텐츠를 자동으로 크롤링하고 새 콘텐츠를 생성함으로써 AIGC 크롤러 애플리케이션을 구축하는 방법입니다. 이 방법은 콘텐츠 생성, 데이터 향상 등과 같이 대량의 콘텐츠 생성이 필요한 애플리케이션 시나리오에 적합합니다. 실제 응용 프로그램에서는 결국 다양한 유형의 크롤러의 요구 사항을 충족하기 위해 크롤링 및 생성 논리를 더욱 정교하게 제어하고 최적화해야 할 수도 있습니다.