gpt4 book ai didi

python - 如何使用crawlspider跳转到下一页?

转载 作者:行者123 更新时间:2023-12-01 02:53:26 24 4
gpt4 key购买 nike

我正在抓取http://www.sephora.com/lipstick使用 scrapy 爬行蜘蛛。我应该如何设置 LinkExtractor 才能废弃所有页面?`

class SephoraSpider(CrawlSpider):
name = "sephora"
# custom_settings = {"IMAGES_STORE": '../images/sephora'}

# allowed_domains = ["sephora.com/"]

start_urls = [
'http://www.sephora.com/lipstick'
# 'http://www.sephora.com/eyeshadow',
# 'http://www.sephora.com/foundation-makeup'
]

rules = (Rule(LinkExtractor(
# restrict_xpaths='//*[@id="main"]/div[4]/div[5]/div[1]/div/div[2]/div[3]/div[7]',
allow=('sephora.com/')
),
callback = 'parse_items',
follow =True),)

def parse(self,response):
# category = ['lipstick']
# for cat in category:
full_url = 'http://www.sephora.com/rest/products/?currentPage=1&categoryName=lipstick&include_categories=true&include_refinements=true'
my_request = scrapy.Request(full_url, callback = 'parse_items')
my_request.meta['page'] = {'to_replace':"currentPage=1"}
yield my_request

def parse_items(self,response):

# cat_json = response.xpath('//script[@id="searchResult"]/text()').extract_first()
# all_url_data = json.loads(cat_json.encode('utf-8'))
# if "products" not in all_url_data:
# return
# products = all_url_data['products']
products = json.loads(response.body)['products']
print(products)
for each_product in products:
link = each_product['product_url']
full_url = "http://www.sephora.com"+link
name = each_product["display_name"]
if 'list_price' not in each_product['derived_sku']:
price = each_product['derived_sku']['list_price_max']
else:
price = each_product['derived_sku']["list_price"]
brand = each_product["brand_name"]
item = ProductItem(
name=name,
price=price,
brand=brand,
full_url=full_url,
category=response.url[23:])
yield item

to_replace = response.meta['page']['to_replace']
cat = response.meta['page']['category']
next_number = int(to_replace.replace("currentPage=", "")) + 1
next_link = response.url.replace(
to_replace, "currentPage=" + str(next_number))
print(next_link)
my_request = scrapy.Request(
next_link,
self.parse_items)
my_request.meta['page'] = {
"to_replace": "currentPage=" + str(next_number),

}
yield my_request

我现在遇到这个错误。

    2017-06-12 12:43:30 [scrapy] DEBUG: Crawled (200) <GET http://www.sephora.com/rest/products/?currentPage=1&categoryName=lipstick&include_categories=true&include_refinements=true> (referer: http://www.sephora.com/makeup-cosmetics)
2017-06-12 12:43:30 [scrapy] ERROR: Spider error processing <GET http://www.sephora.com/rest/products/?currentPage=1&categoryName=lipstick&include_categories=true&include_refinements=true> (referer: http://www.sephora.com/makeup-cosmetics)
Traceback (most recent call last):
File "/Users/Lee/anaconda/lib/python2.7/site-packages/scrapy/utils/defer.py", line 45, in mustbe_deferred
result = f(*args, **kw)
File "/Users/Lee/anaconda/lib/python2.7/site-packages/scrapy/core/spidermw.py", line 48, in process_spider_input
return scrape_func(response, request, spider)
File "/Users/Lee/anaconda/lib/python2.7/site-packages/scrapy/core/scraper.py", line 145, in call_spider
dfd.addCallbacks(request.callback or spider.parse, request.errback)
File "/Users/Lee/anaconda/lib/python2.7/site-packages/twisted/internet/defer.py", line 299, in addCallbacks
assert callable(callback)
AssertionError
2017-06-12 12:43:30 [scrapy] INFO: Closing spider (finished)

最佳答案

简短回答:不要。

长答案:我会采取不同的做法。分页链接不会返回新页面。相反,他们向此 URL 发送 GET 请求:

http://www.sephora.com/rest/products/?currentPage=2&categoryName=lipstick&include_categories=true&include_refinements=true

检查您的网络选项卡并单击分页链接:Networks-Tab

在这里您可以看到浏览器发出的请求和响应。在本例中,单击 pagatinino 链接会生成一个 JSON 对象,其中包含页面上显示的所有产品。

现在查看请求的响应选项卡。在products下可以看到从0到59的数字,这是页面上显示的产品,以及产品的所有信息,例如iddisplay_name 以及,哦,url

尝试右键单击请求并选择在新选项卡中打开以在浏览器中查看响应。现在尝试将丝芙兰主页上的每页项目数设置为不同的内容。你看到会发生什么吗? JSON 对象现在返回更少或更多的项目(取决于您的选择)。

那么我们现在如何处理这些信息呢?

理想情况下,我们可以直接在以下位置请求每个页面的 JSON 对象(只需将请求网址从 current_page=2 更改为 current_page=3)我们的蜘蛛并遵循那里提供的 URL(在 products/n-product/product_url 下),然后抓取各个对象(或者如果您想要的话,只提取产品列表)。

幸运的是,Scrapy(更好,Python)允许您解析 JSON 对象并使用解析的数据执行任何您想要的操作。幸运的是,Sephora 允许您选择显示每页的所有项目,从而将请求 URL 更改为 ?pageSize=-1

您要做的就是产生对产生JSON对象的url的请求,并定义一个处理该对象的解析函数。

只是一个简单的示例,它将提取每个产品的 url 并生成对此 url 的请求(稍后我将尝试提供更详细的示例):

import json

data = json.loads(response.body)
for product in data["products"]:
url = response.urljoin(product["product_url"])
yield scrapy.Request(url=url, callback=self.parse_products)

给你了。学习向网站发出请求确实是值得的,因为您可以轻松地操纵请求 URL,使您的生活更轻松。例如,您可以更改 URL 中的 categoryName 以解析另一个类别。

关于python - 如何使用crawlspider跳转到下一页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44493147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com