Python 크롤러 프레임워크의 스크랩 예제에 대한 자세한 설명
프로젝트 생성
Scrapy는 프로젝트를 생성하는 도구를 제공합니다. 일부 파일은 생성된 프로젝트에 미리 설정되어 있으며 사용자는 이러한 파일에 자신의 코드를 추가해야 합니다.
명령줄을 열고 실행: scrapy startproject tutorial 생성된 프로젝트는 다음
tutorial/
scrapy.cfg
과 유사한 구조를 갖습니다. tutorial/
__init__.py
items.py
Pipelines.py
settings.py
spiders/
__init__.py
… >
name 속성은 매우 중요하며, 서로 다른 스파이더는 동일한 이름을 사용할 수 없습니다.start_urls는 스파이더가 웹 페이지를 크롤링하는 시작점이며, 여러 URL 포함파싱 방법은 스파이더가 하나를 가져오기 위한 것입니다. 콜백은 나중에 웹페이지에서 기본적으로 호출되므로 자신만의 방법을 정의하는 데 이 이름을 사용하지 마세요.from scrapy.spider import BaseSpider class DmozSpider(BaseSpider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): filename = response.url.split("/")[-2] open(filename, 'wb').write(response.body)
스파이더는 URL의 콘텐츠를 가져오면 구문 분석 메서드를 호출하고 응답 매개변수에 전달합니다. 응답에는 캡처된 웹페이지의 콘텐츠가 포함되어 있습니다. 캡처된 웹페이지의 데이터가 내부에서 구문 분석됩니다. 위의 코드는 단순히 웹 페이지 콘텐츠를 파일에 저장합니다.
크롤링 시작명령줄을 열고 생성된 프로젝트 루트 디렉토리 tutorial/을 입력하고 scrapy 크롤링 dmoz를 실행할 수 있습니다. dmoz는 거미.
<🎜를 사용해야 하는 웹 페이지의 데이터를 구문 분석하는 편리한 방법을 제공합니다. > HtmlXPathSelector는 Xpath를 사용하여 데이터를 구문 분석합니다.
//ul/li는 모든 ul 태그 아래에서 li 태그를 선택하는 것을 의미합니다.
a/@href는 모든 a 태그의 href 속성을 선택하는 것을 의미합니다.
from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector class DmozSpider(BaseSpider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): hxs = HtmlXPathSelector(response) sites = hxs.select('//ul/li') for site in sites: title = site.select('a/text()').extract() link = site.select('a/@href').extract() desc = site.select('text()').extract() print title, link, desc
명령줄에서 scrapy를 실행할 때 scrapy가 구문 분석을 사용하도록 두 개의 매개변수를 추가할 수 있습니다. 메소드 반환된 항목은 json 파일로 출력됩니다.
scrapy creep dmoz -o items.json -t json
items.json은 프로젝트의 루트 디렉터리에 배치됩니다
from scrapy.item import Item, Field class DmozItem(Item): title = Field() link = Field() desc = Field() 然后在spider的parse方法中,我们把解析出来的数据保存在DomzItem对象中。 from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from tutorial.items import DmozItem class DmozSpider(BaseSpider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): hxs = HtmlXPathSelector(response) sites = hxs.select('//ul/li') items = [] for site in sites: item = DmozItem() item['title'] = site.select('a/text()').extract() item['link'] = site.select('a/@href').extract() item['desc'] = site.select('text()').extract() items.append(item) return items
scrapy가 웹페이지의 모든 링크를 자동으로 크롤링하도록 허용
위의 예에서 scrapy는 start_urls에 있는 두 URL의 콘텐츠만 크롤링하지만 일반적으로 우리가 원하는 것은 자동으로 스크랩됩니다. 웹 페이지의 모든 링크를 검색한 다음 해당 링크의 콘텐츠를 크롤링합니다. 이를 달성하기 위해 구문 분석 메소드에서 필요한 링크를 추출한 다음 일부 Request 객체를 구성하고 반환하면 Scrapy가 자동으로 이러한 링크를 크롤링합니다. 코드는 유사합니다.
parse는 요청 목록을 반환하는 기본 콜백입니다. Scrapy는 웹 페이지가 캡처될 때마다 자동으로 웹 페이지를 크롤링하고,parse_item이 호출됩니다. 또한 목록을 반환하며, scrapy는 이 목록을 기반으로 웹페이지를 크롤링하고, 가져온 후 pars_details
를 호출하여 이러한 종류의 작업을 더 쉽게 하기 위해 scrapy는 우리가 사용할 수 있는 또 다른 스파이더 기본 클래스를 제공합니다. 이를 편리하게 구현하려면 CrawlSpider
를 사용해야 합니다. BaseSpider와 비교하여 이 속성은 여러 규칙을 포함할 수 있는 목록입니다. 크롤링해야 할 링크와 크롤링하지 않아도 되는 링크를 설명합니다. 이것은 규칙 클래스 http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.contrib.spiders.Ruleclass MySpider(BaseSpider): name = 'myspider' start_urls = ( 'http://example.com/page1', 'http://example.com/page2', ) def parse(self, response): # collect `item_urls` for item_url in item_urls: yield Request(url=item_url, callback=self.parse_item) def parse_item(self, response): item = MyItem() # populate `item` fields yield Request(url=item_details_url, meta={'item': item}, callback=self.parse_details) def parse_details(self, response): item = response.meta['item'] # populate more `item` fields return item
에 대한 문서입니다. 이 규칙은 언제 콜백을 가질 수 있는지 여부를 결정합니다. 콜백이 없으면 scrapy는
pipelines.py 사용
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor class MininovaSpider(CrawlSpider): name = 'mininova.org' allowed_domains = ['mininova.org'] start_urls = ['http://www.mininova.org/today'] rules = [Rule(SgmlLinkExtractor(allow=['/tor/\d+'])), Rule(SgmlLinkExtractor(allow=['/abc/\d+']), 'parse_torrent')] def parse_torrent(self, response): x = HtmlXPathSelector(response) torrent = TorrentItem() torrent['url'] = response.url torrent['name'] = x.select("//h1/text()").extract() torrent['description'] = x.select("//div[@id='description']").extract() torrent['size'] = x.select("//div[@id='info-left']/p[2]/text()[2]").extract() return torrent
항목이 요구 사항을 충족하지 않으면 예외가 발생하고 항목이 json 파일로 출력되지 않습니다.
파이프라인을 사용하려면 settings.py도 수정해야 합니다
라인 추가
from scrapy.exceptions import DropItem class FilterWordsPipeline(object): """A pipeline for filtering out items which contain certain words in their description""" # put all words in lowercase words_to_filter = ['politics', 'religion'] def process_item(self, item, spider): for word in self.words_to_filter: if word in unicode(item['description']).lower(): raise DropItem("Contains forbidden word: %s" % word) else: return item

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

정규 표현식은 프로그래밍의 패턴 일치 및 텍스트 조작을위한 강력한 도구이며 다양한 응용 프로그램에서 텍스트 처리의 효율성을 높입니다.

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

이 기사는 Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask 및 요청과 같은 인기있는 Python 라이브러리에 대해 설명하고 과학 컴퓨팅, 데이터 분석, 시각화, 기계 학습, 웹 개발 및 H에서의 사용에 대해 자세히 설명합니다.

파이썬에서 문자열을 통해 객체를 동적으로 생성하고 메소드를 호출하는 방법은 무엇입니까? 특히 구성 또는 실행 해야하는 경우 일반적인 프로그래밍 요구 사항입니다.
