Python爬取亞馬遜商品列表-xpath(詳情頁爬取待更新...)
阿新 • • 發佈:2018-12-16
一.分析頁面結構
先行爬取首頁內容的兩個欄位,一個是商品名稱title以及價格price;
二.分析頁面的請求:
首先按照PC端的url進行請求,結果未得到返回響應的response的資料,於是通過chrom瀏覽器切換至手機端的來獲取響應:
觀察到其url是編碼過的,對其進行urlencode解碼後,得到url如下:
再對其中的引數進行簡化,方法是刪去url中的部分引數,看原有內容是否會發生變化,最終得到的url為:
因為該亞馬遜網站未進行登陸,故只需新增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)
程式碼如下: