京东网a标签只能读取其属性,不能读取其文本内容
来源:2-9 爬取京东网的数据

py_builder
2020-03-11
京东网爬取不到 评论数量
我已经确定找到了 评论数量的那个 a标签对象, 也能读取 那个a标签的属性,比如 评论地址,,但就是不能读取 a标签对象的 文本,是不是跟 编码 有关系?? 但其它a标签文本都能读取啊,想不明白。
写回答
3回答
-
之所以获取不到评论,是因为京东的反爬机制,第一次加载的HTML中是没有评论数据的,如下图:
评论数据是通过jsonp的方式异步加载过来的,如下图:
022020-03-15 -
py_builder
提问者
2020-03-13
def spider_jd(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' } respond=requests.get(url, headers=headers) respond.encoding= 'utf-8' html_doc =respond.text selector=html.fromstring(html_doc) ul=selector.xpath('//div[@id="J_goodsList"]/ul/li') count=0 for li in ul: count+=1 if count == 1: print('-' * 100) print('-' * 100) else: print('-' * 100) # commerce shop = li.xpath('div/div[@class="p-icons"]/i[@data-tips="京东自营,品质保障"]/text()') commerce=li.xpath('div/div[@class="p-shopnum"]/a/text()')[0] print('商家:{0}'.format(commerce)) if not shop else print('商家:京东自营店') #name name = li.xpath('div/div/a/@title')[0] # title= li.xpath('string(//div/div/a)') print('书名:{0}'.format(name)) #price price=li.xpath('div/div[@class="p-price"]/strong/i/text()')[0] print('价格:{0}元'.format(price)) #comment comment = li.xpath('string(//div/div[@class="p-commit"]/strong/a)') commentlink = li.xpath('div/div[@class="p-commit"]/strong/a/@href')[0] print('评论数量{0}'.format(comment)) # comment = li.xpath('div/div[@class="p-commit"]/strong/a) # 对象是存在的,也能读取其中的属性,就是读取不了其文本 print('评论链接:{0}'.format(commentlink.replace('//', ''))) # print('{0}条评论'.format(comment)) #link link = li.xpath('div/div[@class="p-name"]/a/@href')[0] print('商品链接:{0}'.format(link.replace('//', ''))) #separate print('-'*100) book_list.append({ '商家': '当当自营店' if not shop else commerce, '书名': name, '价格': float(price), '评论': commentlink, '链接': link })
00 -
NavCat
2020-03-13
把你的代码,贴出来,我帮你调试下:
在这里贴
012020-03-13
相似问题