Scrapy 抓取多个页面
Scrapy scrape multiple pages
我有一个可以抓取单个页面的功能。如何在点击相应链接后抓取多个页面?我是否需要像下面的 gotoIndivPage() 这样调用 parse() 的单独函数?谢谢!
import scrapy
class trainingScraper(scrapy,Spider):
name = "..."
start_urls = "url with links to multiple pages"
# for scraping individual page
def parse(self,response):
SELECTOR1 = '.entry-title ::text'
SELECTOR2 = '//li[@class="location"]/ul/li/a/text()'
yield{
'title': response.css(SELECTOR1).extract_first(),
'date': response.xpath(SELECTOR2).extract_first(),
}
def gotoIndivPage(self,response):
PAGE_SELECTOR = '//h3[@class="entry-title"]/a/@href'
for page in response.xpath(PAGE_SELECTOR):
if page:
yield scrapy.Request(
response.urljoin(page),
callback=self.parse
)
我通常会为每个不同类型的 HTML 我试图抓取的结构创建一个新函数。因此,如果您的链接将您带到一个 HTML 结构与起始页不同的页面,我会创建一个新函数并将其传递给我的回调。
def parseNextPage(self, response):
# Parse new page
def parse(self,response):
SELECTOR1 = '.entry-title ::text'
SELECTOR2 = '//li[@class="example"]/ul/li/a/text()'
yield{
'title': response.css(SELECTOR1).extract_first(),
'date': response.xpath(SELECTOR2).extract_first(),
}
href = //li[@class="location"]/ul/li/a/@href
yield scrapy.Request(
url = href,
callback=self.parseNextPage
)
我有一个可以抓取单个页面的功能。如何在点击相应链接后抓取多个页面?我是否需要像下面的 gotoIndivPage() 这样调用 parse() 的单独函数?谢谢!
import scrapy
class trainingScraper(scrapy,Spider):
name = "..."
start_urls = "url with links to multiple pages"
# for scraping individual page
def parse(self,response):
SELECTOR1 = '.entry-title ::text'
SELECTOR2 = '//li[@class="location"]/ul/li/a/text()'
yield{
'title': response.css(SELECTOR1).extract_first(),
'date': response.xpath(SELECTOR2).extract_first(),
}
def gotoIndivPage(self,response):
PAGE_SELECTOR = '//h3[@class="entry-title"]/a/@href'
for page in response.xpath(PAGE_SELECTOR):
if page:
yield scrapy.Request(
response.urljoin(page),
callback=self.parse
)
我通常会为每个不同类型的 HTML 我试图抓取的结构创建一个新函数。因此,如果您的链接将您带到一个 HTML 结构与起始页不同的页面,我会创建一个新函数并将其传递给我的回调。
def parseNextPage(self, response):
# Parse new page
def parse(self,response):
SELECTOR1 = '.entry-title ::text'
SELECTOR2 = '//li[@class="example"]/ul/li/a/text()'
yield{
'title': response.css(SELECTOR1).extract_first(),
'date': response.xpath(SELECTOR2).extract_first(),
}
href = //li[@class="location"]/ul/li/a/@href
yield scrapy.Request(
url = href,
callback=self.parseNextPage
)