python爬取京東所有iphone的價格和名稱
來源:程序員人生 發(fā)布時間:2015-08-19 07:42:25 閱讀次數(shù):2981次
本來想升1下級,用1下creep神馬的,但是正則今天突然出了點小問題,我就生氣了,就用正則抓取了1下。
這個正則可以用re.search 或 re.findall都可以,我比較喜歡用search由于可以直接提取結(jié)果不用在過濾了。
代碼以下,這個小爬爬比較簡單。
#-*- coding:utf⑻ -*-
import urllib2
import json
import re
SearchIphoneUrl = 'http://search.jd.com/Search?keyword=%E8%8B%B9%E6%9E%9C%E6%89%8B%E6%9C%BA&enc=utf⑻&qr=&qrst=UNEXPAND&as_key=title_key%2C%2C%E6%89%8B%E6%9C%BA&rt=1&stop=1&click=&psort=1&page=1'
header = {'User-Agent':'User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 SE 2.X MetaSr 1.0','Accept':'*/*'}
def getHtmlSrc(url,header):
req = urllib2.Request(url,header)
res = urllib2.urlopen(url,timeout = 5)
htmlSrc = res.read()
return htmlSrc
def saveHtmlSrc(url):
html = getHtmlSrc(url,header)
with open('jd_iphone.txt','w') as f:
f.write(html)
saveHtmlSrc(SearchIphoneUrl)
print '++++++++++++++++++++京東放養(yǎng)的爬蟲++++++++++++++++++++'
with open('jd_iphone.txt','r') as fhtml:
localhtml = fhtml.read()#.replace("'",'"').replace(' ','')
for skuid in re.findall('<li sku="d+" >',localhtml):
#商品編號
sku = skuid.split('"')[1]
#手機名稱
pname = re.search('''<font class="skcolor_ljg">蘋果</font>(.*?)<font class="skcolor_ljg">手機</font>(.*?)<font class='adwords' id='AD_%s'></font>''' % sku,localhtml) #
正則取商品名稱html
#手機價格
price = re.search('''<strong class="J_%s" data-price="(.*?)">'''%sku,localhtml)
if(pname!='' and price!=''):
print "商品編號:%s"%sku
print "名稱:%s
價格:%s
"%(pname.group(1),price.group(1))
print '++++++++++++++++++++京東放養(yǎng)的爬蟲++++++++++++++++++++'
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈