python爬取天猫,python如何爬取天猫店铺商品链接?
在使用python爬蟲爬取網(wǎng)頁時會遇到很多含有特殊符號的情況,當(dāng)把鏈接復(fù)制到瀏覽器打開,發(fā)現(xiàn)每個節(jié)點(diǎn)都多了個\,直接使用response.xpath()無法定位元素,為避免定位不到元素的問題,應(yīng)先對響應(yīng)內(nèi)容做一下過濾,然后使用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爬蟲學(xué)習(xí)推薦:python爬蟲教程。
總結(jié)
以上是生活随笔為你收集整理的python爬取天猫,python如何爬取天猫店铺商品链接?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Telegram 搜索机器人BOT
- 下一篇: python用folium绘制地图并设置