Python爬取亚马逊商品列表-xpath(详情页爬取待更新...)

一.分析页面结构

先行爬取首页内容的两个字段,一个是商品名称title以及价格price;

二.分析页面的请求:

首先按照PC端的url进行请求,结果未得到返回响应的response的数据,于是通过chrom浏览器切换至手机端的来获取响应:

观察到其url是编码过的,对其进行urlencode解码后,得到url如下:

再对其中的参数进行简化,方法是删去url中的部分参数,看原有内容是否会发生变化,最终得到的url为:

https://www.amazon.cn/gp/aw/s/ref=is_pg?rh=i:aps,k:华为手机

因为该亚马逊网站未进行登陆,故只需添加headers,而不用添加cookies,最终拿到html

三.xpath分析

通过copy xpath获取单独的xpath后,由ctrl + f 将后面的标号去掉至1 of all ,进而获取全部数据

拿到的数据由字典方式存储,根据页面中的url变化,改变参数的page值来进行访问;

最终结果:

详情页的分析中发现其使用了js进行加载,暂时只想到用senlenium的思路,后续补上

import requests
from lxml import etree
from requests.exceptions import RequestException
from urllib.parse import urljoin
from multiprocessing import Pool

from settings import *

def get_one_page(url,headers,cookies):
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None
def parse_one_page(res):

    html = etree.HTML(res)
    title = html.xpath('//*[@id="resultItems"]/li/a/div/div/h5/span/text()')
    price = html.xpath('//*[@id="resultItems"]/li/a/div/div/div/div/span[1]/text()')
    for i in range(len(price)):
        phone = {}
        phone['title'] = title[i]
        phone['price'] = price[i].replace(',','')
        yield phone
def main(num):
    url = 'https://www.amazon.cn/gp/aw/s/ref=is_pg?rh=i%3Aaps%2Ck%3A%E5%8D%8E%E4%B8%BA%E6%89%8B%E6%9C%BA&page={}'.format(num)
    response = get_one_page(url,headers,cookies)
    # print(response)
    result = parse_one_page(response)
    result = list(result)
    print(result)
if __name__ == '__main__':
    for i in range(10):
        main(i+1)

代码如下:

 

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

精神抖擞王大鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值