python爬取京东商品信息代码_爬取京东商品信息

利用 BeautifulSoup + Requests 爬取京东商品信息并保存在Excel中

一、查看网页信息

打开京东商城,随便输入个商品,就选固态硬盘吧

先看看 URL 的规律,可以看到我们输入的关键词是在 keyword 后面

试试删掉后面的一些字符,发现并不影响我们的访问,所以我们的 URL 可以简化成下面这个样子

复制下链接,发现简化后的 URL 是酱紫的https://search.jd.com/Search?keyword=%E5%9B%BA%E6%80%81%E7%A1%AC%E7%9B%98&enc=utf-8

keyword后面的“固态硬盘”变成了这个

%E5%9B%BA%E6%80%81%E7%A1%AC%E7%9B%98

这是因为网址中的中文会被编码成UTF-8,每个中文3个字节,每个字节前加上%号。编码和解码方法如下:

>>> import urllib

>>>urllib.parse.unquote('%E5%9B%BA%E6%80%81%E7%A1%AC%E7%9B%98')

'固态硬盘'

>>> urllib.parse.quote('固态硬盘')

'%E5%9B%BA%E6%80%81%E7%A1%AC%E7%9B%98'

那我们就可以写出搜索商品名对应请求的 URL:

def get_good_url(word):

url_str = urllib.parse.quote(word)

url = "https://search.jd.com/Search?keyword={}&enc=utf-8".format(url_str)

return url

二、爬取信息

接着来看看我们所需爬取商品的信息

选中一个商品,右键检查

再检查下第二个商品,查看下规律,我们可以发现每个商品信息,都存在下面这个 class 里。所以我们就可以用BeautifulSoup的 find_all(class_="gl-i-wrap") 找出所有的商品,生成一个列表,再从中找出每个商品对应的信息

但点开这个标签后,如下图,我们可以发现,我们索要爬取商品信息都存在一样的标签内。

所以我们也可以先找出所有的 name,price,commit,img,生成四个列表,再把它们一一对应

三、生成代码

import requests

from bs4 import BeautifulSoup

import urllib

headers = { #加个请求头伪装浏览器

"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"

}

def get_good_url(word):

url_str = urllib.parse.quote(word)

url = "https://search.jd.com/Search?keyword={}&enc=utf-8".format(url_str)

return url

def get_html(url):

html = requests.get(url, headers=headers)

html.encoding = html.apparent_encoding #html.apparent_encoding为从请求返回的内容分析出的编码格式,此处转为'utf-8'

soup = BeautifulSoup(html.text, 'lxml')

return soup

#all_goods = soup.find_all(class_='gl-i-wrap') 另一种查找方法

def get_info(soup):

titles = soup.find_all(class_="p-name p-name-type-2")

prices = soup.find_all(class_="p-price")

commits = soup.find_all(class_="p-commit")

imgs = soup.find_all(class_="p-img")

for title, price, commit, img in zip(titles, prices, commits, imgs):

data = {

'title' : title.text.strip(),

'price' : price.text.strip(),

'commit': commit.text.strip(),

'link' : img.find_all('a')[0].get("href"),

'img' : img.find_all('img')[0].get("src")

}

print(data)

if __name__ == '__main__':

good = input("请输入你要查询的商品\n")

link = get_good_url(good)

html = get_html(link)

get_info(html)

运行下试试看:

>>>

=================== RESTART: C:/Users/Why Me/Desktop/jd.py ===================

请输入你要查询的商品

固态硬盘

{'commit': '已有6.4万+人评价', 'link': '//item.jd.com/2010277.html', 'price': '¥469.00', 'title': '三星(SAMSUNG) 750 EVO 120G SATA3 固态硬盘', 'img': '//img12.360buyimg.com/n7/jfs/t2212/266/1035221213/221087/773b0946/563977ac

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值