Flipkart.com产品'价格'和产品'标题'使用Python提取 [英] Flipkart.com product 'price' and product 'title' extraction using Python

查看:71
本文介绍了Flipkart.com产品'价格'和产品'标题'使用Python提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下Python代码,以从flipkart.com

I have written the following Python code to extract the PRICE of the item specified from flipkart.com

import urllib2
import bs4
import re

item="Wilco Classic Library: Autobiography Of a Yogi (Hardcover)"
item.replace(" ", "+")
link = 'http://www.flipkart.com/search/a/all?query={0}&vertical=all&dd=0&autosuggest[as]=off&autosuggest[as-submittype]=entered&autosuggest[as-grouprank]=0&autosuggest[as-overallrank]=0&autosuggest[orig-query]=&autosuggest[as-shown]=off&Search=%C2%A0&otracker=start&_r=YSWdYULYzr4VBYklfpZRbw--&_l=pMHn9vNCOBi05LKC_PwHFQ--&ref=a2c6fadc-2e24-4412-be6a-ce02c9707310&selmitem=All+Categories'.format(item)
r = urllib2.Request(link, headers={"User-Agent": "Python-urlli~"})
try:
    response = urllib2.urlopen(r)
except:
    print "Internet connection error"  
thePage = response.read()
soup = bs4.BeautifulSoup(thePage)
firstBlockSoup = soup.find('div', attrs={'class': 'fk-srch-item'})
priceSoup=firstBlockSoup.find('b',attrs={'class':'fksd-bodytext price final-price'})
price=priceSoup.contents[0]
print price

titleSoup=firstBlockSoup.find('a',attrs={'class':'fk-srch-title-text fksd-bodytext'})
title=titleSoup.findAll('b')
print title

上面的代码在执行时可以毫无问题地打印PRICE.

The above code when executed prints the PRICE without issues.

Rs. 138 

但是标题如下:

[<b>Wilco</b>, <b>Classic</b>, <b>Library</b>, <b>Autobiography</b>, <b>Of</b>, <b>a</b>, <b>Yogi</b>, <b>Hardcover</b>] 

如果您查看

The reason will be apparent if you have a look at the source code of the product page (use 'Inspect element')

现在,如何提取正确格式的TITLE以进行打印:

Now, How do I extract the TITLE in a proper format so as to print:

Wilco Classic Library: Autobiography Of a Yogi (Hardcover)

推荐答案

只需对 titleSoup

>>> titleSoup=firstBlockSoup.find('a',attrs={'class':'fk-srch-title-text fksd-bodytext'})
>>> titleSoup.text
u'Wilco Classic Library: Autobiography Of a Yogi (Hardcover)'

这也将起作用:

invalid_tags = ['b']
titleSoup=firstBlockSoup.find('a',attrs={'class':'fk-srch-title-text fksd-bodytext'})

for tag in invalid_tags: 
    for match in titleSoup.findAll(tag):
       match.replaceWithChildren()
print "".join(titleSoup.contents)

这篇关于Flipkart.com产品&amp;#39;价格&amp;#39;和产品&amp;#39;标题&amp;#39;使用Python提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆