注册

通过淘宝数据爬虫学习python scrapy requests与response对象

通过淘宝数据爬虫学习Python Scrapy Requests与Response对象的攻略,可以分为以下几个步骤:

安装Requests模块

首先需要安装Requests模块,可以通过命令行在Python环境下安装:

pip install requests

发送请求获取页面

使用Requests模块发送请求,获取淘宝某个商品的页面:

import requests

url = 'https://s.taobao.com/search?q=python'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)

print(response.text)

通过以上代码,可以获取淘宝中搜索“python”商品的页面信息。

解析页面

获取到页面信息后,需要对页面进行解析。这可以使用XPath语法进行解析,例如:

from lxml import etree

html = etree.HTML(response.text)

items = html.xpath('//div[@class="item J_MouserOnverReq  "]')

for item in items:
    title = item.xpath('.//a[@class="J_ClickStat"]//@title')[0]
    price = item.xpath('.//div[@class="price g_price g_price-highlight"]//text()')[0]
    print(title, price)

以上代码中,通过XPath语法,选取了搜索结果中的商品列表和商品的名称、价格信息,并进行了输出。

使用Scrapy框架优化代码

Scrapy是Python中流行的爬虫框架,可以帮助开发者更快速便捷地编写爬虫程序。

通过Scrapy框架,对以上代码进行优化:

import scrapy
from scrapy import Selector


class TaobaoSpider(scrapy.Spider):
    name = 'taobao'
    allowed_domains = ['taobao.com']

    def start_requests(self):
        urls = ['https://s.taobao.com/search?q=python']
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        sel = Selector(text=response.body)
        items = sel.xpath('//div[@class="item J_MouserOnverReq  "]')
        for item in items:
            title = item.xpath('.//a[@class="J_ClickStat"]//@title')[0].extract()
            price = item.xpath('.//div[@class="price g_price g_price-highlight"]//text()')[0]
            print(title, price)

以上代码中,通过Scrapy框架中的Selector解析器,选取了搜索结果中的商品列表和商品的名称、价格信息,并进行了输出。同时通过使用Scrapy框架的异步处理能力,减少了请求的时间和提高了效率。

以上,就是通过淘宝数据爬虫学习Python Scrapy Requests与Response对象的完整攻略。