书包的全部信息都在div标签,属性是gl-i-wrap中,(这个标签太长,我只截图了一部分)
书包价格放在了div标签,属性是p-price中,且在em标签下的文本信息中
书包价格放在了div标签,属性是p-name p-name-type-2中,且在em标签下的文本信息中
综上所述,利用信息提取(嵩老师的课程有介绍信息提取的相关方法)的方法就可以找到对应商品信息文本
代码如下
import requests
from bs4 import BeautifulSoup
def getHTMLText(url):
try:
header = {'user-agent': 'Mozilla/5.0'}
r = requests.get(url,headers=header)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def getStockList(html):
try:
if html=='':
print('页面不存在')
infodict = {}
soup = BeautifulSoup(html, 'html.parser')
for i in range(20):
info = soup.find_all('div',attrs={'class':"gl-i-wrap"})[i]
info_price = info.find_all('div',attrs={'class':"p-price"})[0]
info_name = info.find_all('div',attrs={'class':"p-name p-name-type-2"})[0]
valuelist = info_price.find_all('i')
keylist = info_name.find_all('em')
for i in range(len(keylist)):
key = keylist[i].text
val = valuelist[i].text
infodict[key] = val
return infodict
except:
return ""
def printGoodsList(ilt):
tplt = "{:4}\t{:20}\t{:4}\t"
print(tplt.format("序号", "商品名称",'价格'))
count = 0
for g in ilt:
count = count + 1
print(tplt.format(count, g, ilt[g]))
def main():
words = '书包'
stock_list_url = 'https://search.jd.com/Search?keyword='
url = stock_list_url + words
html = getHTMLText(url)
dict1 = getStockList(html)
printGoodsList(dict1)
main()