京东的爬取不出来
来源:2-9 爬取京东网的数据

慕娘5291559
2020-06-24
老师你好,我按照你的代码在python上跑,发现跑出不来,请你帮我看看好吗,我是python 3.8:
def spider(sn, book_list=[]):
""" 爬取京东商城的图书信息 “”"
url = ‘https://search.jd.com/Search?keyword={0}’.format(sn)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}
# 获取HTML信息
html_data = requests.get(url, headers=headers).text
# print(html_data)
# 获取xpath对象
selector = html.fromstring(html_data)
# 寻找书本列表
ul_list = selector.xpath('//div[@id="J_goodsList"]/ul/li')
print(len(ul_list))
# 解析对应的内容,标题,价格,链接
for li in ul_list:
# 标题
title = li.xpath('div/div[@class="p-name"]/a/@title')
print(title[0])
# 购买链接
link = li.xpath('div/div[@class="p-name"]/a/@href')
print(link[0])
# 价格
price = li.xpath('div/div[@class="p-price"]/strong/i/text()')
print(price[0])
# 店铺
store = li.xpath('div//a[@class="curr-shop"]/@title')
print(store[0])
book_list.append({
'title': title[0],
'price': price[0],
'link': link[0],
'store': store[0]
})
if name == ‘main’:
sn = '9787115428028’
spider(sn)
报错信息如下:
Traceback (most recent call last):
File “C:/Users/jiami/PycharmProjects/book/spider_jd.py”, line 48, in
spider(sn)
File “C:/Users/jiami/PycharmProjects/book/spider_jd.py”, line 36, in spider
print(store[0])
IndexError: list index out of range
谢谢老师哈
写回答
1回答
-
京东网站更新了,页面结构发生了编码,试试最新的代码:
import requests from lxml import html def spider(sn, book_list=[]): """ 爬取京东的图书数据 """ url = 'https://search.jd.com/Search?keyword={0}'.format(sn) # 获取HTML文档 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36' } resp = requests.get(url, headers=headers) print(resp.encoding) resp.encoding = 'utf-8' html_doc = resp.text # print(html_doc) # 获取xpath对象 selector = html.fromstring(html_doc) # 找到列表的集合 ul_list = selector.xpath('//div[@id="J_goodsList"]/ul/li') print(len(ul_list)) # 解析对应的内容,标题,价格,链接 for li in ul_list: # 标题 title = li.xpath('div/div[@class="p-name"]/a/@title') print(title[0]) # 购买链接 link = li.xpath('div/div[@class="p-name"]/a/@href') print(link[0]) # 价格 price = li.xpath('div/div[@class="p-price"]/strong/i/text()') print(price[0]) # 店铺 store = li.xpath('div//a[@class="curr-shop hd-shopname"]/@title') print(store[0]) book_list.append({ 'title': title[0], 'price': price[0], 'link': link[0], 'store': store[0] }) if __name__ == '__main__': spider('9787115428028')
132020-07-06
相似问题