python爬取天猫,python如何爬取天猫店铺商品链接?

a7e9fde978ef87d2bda2eddad063c956.png

在使用python爬虫爬取网页时会遇到很多含有特殊符号的情况,当把链接复制到浏览器打开,发现每个节点都多了个\,直接使用response.xpath()无法定位元素,为避免定位不到元素的问题,应先对响应内容做一下过滤,然后使用response.replace()将过滤后的html文档重新赋值给response,本文以爬取天猫店铺商品链接为例,向大家介绍爬取过程。

爬取思路

1、使用response.text获取html文本,去除其中的\;

2、使用response.replace() 重新将去除\后的html赋值给response;

3、使用response.xpath()定位元素,成功获取商品链接。

具体代码# -*- coding: utf-8 -*-

import re

import scrapy

class TmallSpider(scrapy.Spider):

name = 'tmall'

allowed_domains = ['tmall.com']

start_urls = [

'https://wogeliou.tmall.com/i/asynSearch.htm?_ksTS=1611910763284_313&callback=

jsonp314&mid=w-22633333039-0&wid=22633333039&path=/search.htm&search=y&spm=a220o.1000855.0.0.7fcc367fsdZyLF'

]

custom_settings = {

'ITEM_PIPELINES': {

'tn_scrapy.pipelines.TnScrapyPipeline': 300,

},

'DEFAULT_REQUEST_HEADERS': {

"user-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)

Chrome/78.0.3904.70 Safari/537.36',

'cookie': '登录后的cookie'

}

}

def parse(self, response):

html = re.findall(r'jsonp\d+\("(.*?)"\)', response.text)[0]

# 替换掉 \

html = re.sub(r'\\', '', html)

# print('html:', html)

response = response.replace(body=html)

link = response.xpath('//div[@class="item5line1"]/dl/dd[@class="detail"]/a/@href').extract()

print('link: ', link)

以上就是python爬取天猫店铺商品链接的介绍,大家可以套入代码直接使用哦~更多python爬虫学习推荐:python爬虫教程。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值