京东手机信息爬取

京东商城有很多商品信息可供爬取,这次主要爬取全部手机综合排序的第一页

一、相关爬取页面分析

页面地址:

https://list.jd.com/list.html?cat=9987,653,655

京东手机信息爬取

对应源码:

京东手机信息爬取

其中价格、评论数需要动态获取

先来看价格信息,访问的URL格式为

https://p.3.cn/prices/mgets?skuIds=J_data-sku

括号里的data-sku为商品id,打开url返回

再看评论信息,访问的URL格式为

https://club.jd.com/comment/productCommentSummaries.action?referenceIds=data-sku

括号里的data-sku为商品id,打开url返回

京东手机信息爬取

二、python3代码说明

爬取思路:

1、 爬取该网页的源代码(前述分析,函数模块getHTMLText(url))

def getHTMLText(url):
try:
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' #模拟浏览器登陆
headers = {'User-Agent': user_agent}
r = requests.get(url, headers = headers)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ''

2、用 Beautiful Soup提取所需内容

3、 根据网页源代码对所取内容进行精准修改以获取所需内容

def get_info(url):
html = getHTMLText(url)

#创建 beautifulsoup 对象
soup = BeautifulSoup(html,'lxml')

items = soup.select('li.gl-item')
results = []

for item in items:
item_url = 'http:' + item.find('div', class_='p-name').find('a')['href']
name = (item.find('div', class_='p-name').find('em').string).strip()
data_sku = item.find('div', class_='p-focus').find('a')['data-sku']
price_url = 'https://p.3.cn/prices/mgets?skuIds=J_' + str(data_sku)
price = requests.get(price_url).json()[0]['p']
commit_url = 'https://club.jd.com/comment/productCommentSummaries.action?referenceIds=' + str(data_sku)
comments = requests.get(commit_url).json()['CommentsCount'][0]['CommentCountStr']
shop_name = item.find('div', class_='p-shop')['data-shop_name']
results.append([name, item_url, data_sku, price, comments, shop_name])
return results

  4、把内容写入到文件

def save_to_csv(results):
path = 'E:/京东商品信息爬取/'
if not os.path.exists(path):
os.mkdir(path)
with open(path + datetime.now().strftime('%Y-%m-%d %H-%M-%S') + '京东手机信息.csv', 'w') as f:
writer = csv.writer(f, lineterminator='\n')
writer.writerow(['商品', '链接', 'ID', '价格', '评论数', '店铺'])
writer.writerows(results)

主要代码(jdspider.py)

https://github.com/zhhaoqin/jdspider

三、结果

京东手机信息爬取


四、小结

实现了一个爬虫的基本功能,后续可根据需要在此基础上进行扩充完善,例如多线程的并发爬取,验证码交互等。