天天看點

Python3.x學習筆記[1]:2種簡單爬蟲擷取京東價格

因為隻是初學,是以沒有借助beautiful soup4和Scrapy這些庫,隻用到了re與urllib這兩個内置庫和一些built-in functions

以下内容學自網絡

方法一:通過京東移動商城(因為它沒有把價格藏在js中)

# codeing=utf-8
import urllib.request
import re
#通過京東移動接口
url = 'http://item.jd.com/997951.html'#原本的網址
jdid = re.search(r'/(\d+)\.html',url).group(1)#原本的網址提取出商品ID,即997951


url = 'http://m.jd.com/product/'+str(jdid)+'.html'#轉換成為移動商城的url
html = urllib.request.urlopen(url).read().decode('utf-8')#通過對源代碼進行utf-8解碼
aa = re.findall(r'<font color="red" style="font-family:Arial;font-weight:bold;font-size:18px">&.*</font>', html)[0]#這裡使用的是findall,可以用别的

aa = re.findall(r'\d+\.\d+', aa)#有點多此一舉,不過當時還不太熟悉re.search
print (aa[0])
           

方法二:通過京東商城的json檔案查,具體如何擷取,可以用火狐浏覽器嗅出來

# codeing=utf-8
import urllib.request
import re
'''通過京東伺服器查'''
url = 'http://item.jd.com/997951.html'
jdid = re.search(r'/(\d+)\.html', url).group(1)

url = 'http://p.3.cn/prices/get?skuid=J_' + \
    str(jdid) + '&type=1&area=19_1601_51091&callback=cnp'#這就是那個被藏起來的json檔案,格式除了京東id部分其他都一樣
#其實就是p.3.cn/prices/get?skuid=J_997951&type=1&area=19_1601_51091&callback=cnp
html = urllib.request.urlopen(url).read().decode('utf-8')
aa = re.search(r'"p":"(.*?)"', html).group(1)

print(aa)