【发布时间】:2018-01-24 17:11:43
【问题描述】:
我在开发爬虫时需要指导。
我需要构建一个自定义抓取工具,从 3 个电子商务网站检索所有产品。
我用 Scrapy 构建了 PoC 刮板,但是,这个刮板有一个流程:
抓取工具需要将给定类别抓取到抓取深度级别 3,才能到达并访问我需要的页面,这些页面的深度级别为 1。
例如,抓取需要遵循这个顺序:
开始:domain.com
domain.com/category/sub_categry/mini_sub_category
domain.com/product1 和 domain.com/product2
product1 和 product2 的网址只有在达到深度级别 2(爬取子类别)时才能访问。
我的问题是我是否可以自定义 scrapy 以自动遵循此顺序或我是否需要使用 Beautifouldsoup 自定义构建一个刮板并手动提供每个 sub_category 并让 bs4 从那里开始刮? p>
这是我的 Scrapy 代码
class DomainsSpider(CrawlSpider):
name = 'domains'
allowed_domains = ['www.amazon.com']
start_urls = ['http://www.amazon.com/']
rules = [Rule(LinkExtractor(canonicalize=True, unique=True),follow=True, callback="parse_items")]
def parse_items(self, response):
# create the soup for the domain
soup = BeautifulSoup(response.text, 'html.parser')
#check if proxy is working
if not soup.title.string:
yield Request(url=response.url, dont_filter=True)
#extract the title
heading_1_raw = response.selector.xpath('//h1/text()').extract()
heading_1_strip = [s.strip() for s in heading_1_raw]
heading_1 = []
for h1_text in range(0, len(heading_1_strip)):
if str(heading_1_strip[h1_text]) != "":
heading_1.append(heading_1_strip[h1_text])
price_raw = response.selector.xpath('//p[contains(@class, "product-new-price")]//text()').extract()
product_code_text = soup.find_all(string=re.compile("Cod produs"))
yield {
'url' : response.url,
'page_title': soup.title.string,
#'h1': h1s[0],
'h1' : heading_1[0],
'price' : price_raw,
'product_code' : product_code_text
}
【问题讨论】:
标签: python beautifulsoup scrapy logic