我需要一个 Scrapy 蜘蛛为每个 URL(30 个产品,所以 30 个 url)抓取以下页面(https://www.phidgets.com/?tier=1&catid=64&pcid=57),然后通过该 url 进入每个产品并抓取其中的数据。
我的第二部分完全按照我的意愿工作:
import scrapy
class ProductsSpider(scrapy.Spider):
name = "products"
start_urls = [
'https://www.phidgets.com/?tier=1&catid=64&pcid=57',
]
def parse(self, response):
for info in response.css('div.ph-product-container'):
yield {
'product_name': info.css('h2.ph-product-name::text').extract_first(),
'product_image': info.css('div.ph-product-img-ctn a').xpath('@href').extract(),
'sku': info.css('span.ph-pid').xpath('@prod-sku').extract_first(),
'short_description': info.css('div.ph-product-summary::text').extract_first(),
'price': info.css('h2.ph-product-price > span.price::text').extract_first(),
'long_description': info.css('div#product_tab_1').extract_first(),
'specs': info.css('div#product_tab_2').extract_first(),
}
# next_page = response.css('div.ph-summary-entry-ctn a::attr("href")').extract_first()
# if next_page is not None:
# yield response.follow(next_page, self.parse)
但我不知道如何做第一部分。正如您将看到的,我将主页 ( https://www.phidgets.com/?tier=1&catid=64&pcid=57) 设置为 start_url。但是我如何让它用我需要抓取的所有 30 个 url 填充 start_urls 列表?
最佳答案
我目前无法测试,所以如果这对您有用,请告诉我,如果有任何错误,我可以对其进行编辑。
这里的想法是我们找到第一页中的每个链接并产生新的 scrapy 请求,将您的产品解析方法作为回调传递
import scrapy
from urllib.parse import urljoin
class ProductsSpider(scrapy.Spider):
name = "products"
start_urls = [
'https://www.phidgets.com/?tier=1&catid=64&pcid=57',
]
def parse(self, response):
products = response.xpath("//*[contains(@class, 'ph-summary-entry-ctn')]/a/@href").extract()
for p in products:
url = urljoin(response.url, p)
yield scrapy.Request(url, callback=self.parse_product)
def parse_product(self, response):
for info in response.css('div.ph-product-container'):
yield {
'product_name': info.css('h2.ph-product-name::text').extract_first(),
'product_image': info.css('div.ph-product-img-ctn a').xpath('@href').extract(),
'sku': info.css('span.ph-pid').xpath('@prod-sku').extract_first(),
'short_description': info.css('div.ph-product-summary::text').extract_first(),
'price': info.css('h2.ph-product-price > span.price::text').extract_first(),
'long_description': info.css('div#product_tab_1').extract_first(),
'specs': info.css('div#product_tab_2').extract_first(),
}
关于python - 使用 scrapy 获取 url 列表,然后在这些 url 中抓取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913798/