首页 文章详情

python爬虫学习教程:如何爬取天猫店铺商品链接?

python教程 | 427 2021-08-02 10:06 0 0 0
UniSMS (合一短信)

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

爬取思路


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


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


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


具体代码

# -*- coding: utf-8 -*-import reimport 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爬取天猫店铺商品链接的介绍

*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权

ps:零基础系统放爬虫教程可以关注我公众号



good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter