【问题标题】:Scrape categories and its urls from alibaba and put it in two column从阿里巴巴抓取类别及其网址并将其放在两列中
【发布时间】:2018-08-31 19:43:24
【问题描述】:

您好,我是 scrapy 的新手,我正在尝试从阿里巴巴的 Product By categories 页面抓取类别和类别的 URL。我正在尝试将其抓取并放在 CSV 文件中。

当我在电子表格中打开它时,我想给出的视图是:-

categories                           categories_urls

Agricultural Growing Media           its URL
Animal Products                      its URL
.                                    .
.                                    .
.                                    .

代码:-

# -*- coding: utf-8 -*-
import scrapy

class AlibabaCatagoriesSpider(scrapy.Spider):
name = 'alibaba_catagories'
allowed_domains = ['alibaba.com']
start_urls = ['https://www.alibaba.com/Products?spm=a2700.8293689.scGlobalHomeHeader.352.2ce265aa7GOmOF']

def parse(self, response):
    a = response.css('ul.sub-item-cont')
    for catag in a:
        item = {
           'categories': catag.css('li>a::text').extract(),
           'categories_url': catag.css('li>a::attr(href)').extract()
            }
        yield item

问题

  • \n 并且在抓取类别时会抓取空白。
  • 数据未以理想的格式抓取

你能提供什么帮助

  • 修改代码以便我们可以拥有
  • 提供在抓取时删除 \n 和空白的技巧

理想的格式。

【问题讨论】:

  • “理想的格式”是什么意思?
  • 我想在一个页面中显示类别的名称,在另一个页面中显示它们的 URL。

标签: python xpath web-scraping scrapy css-selectors


【解决方案1】:

使用 Scrapy 非常简单:

def parse(self, response):

    for category_node in response.xpath('//ul[contains(@class, "sub-item-cont")]/li/a'):

        item = {
           'categories': category_node.xpath('./text()').extract_first().strip(),
           'categories_url': category_node.xpath('./@href').extract_first()
        }
        yield item

【讨论】:

  • 嗨,先生,我正在尝试实现同样的事情,请看这个 --> question
【解决方案2】:
import requests
from bs4 import BeautifulSoup
def parser():
    url = 'https://www.alibaba.com/Products?spm=a2700.8293689.scGlobalHomeHeader.352.2ce265aa7GOmOF'
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text, "html.parser")
    name_dict = {}
    for l in soup.find_all('li'):
        content = l.find('a')
        if content:
            href = content.get('href')
            name = content.get_text()
            if href.find('_pid') != -1:
            name_dict[name] = href
    return name_dict

这是由 BeautifulSoup 模块制作的,因为它更容易抓取。该函数将返回一个字典,其中键为名称,值为 url。

【讨论】:

    【解决方案3】:

    您必须使用 normalize-space 功能来删除空格。 .css 选择器不可用或非常复杂。我建议你使用XPath。 如此处所述。 normalize-space just works with xpath not css selector

    使用归一化空间函数的 Xpath 示例

     Product=   response.xpath('normalize-space(//*[@class="column one3"]/a/@href)').extract()
    

    【讨论】:

      【解决方案4】:

      尝试跟随选择器

      list(map(lambda x: x.replace('\n', '').strip(), response.xpath('//*[@class="cg-main"]//*[contains(@class, "sub-item-cont")]//li/a[@href]/text()').extract()))
      

      【讨论】:

        最近更新 更多