利用 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