3

我编写了以下 Python 代码来提取从 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 没有问题。

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>] 

如果您查看产品页面的源代码,原因就会很明显(使用“检查元素”)

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

Wilco Classic Library: Autobiography Of a Yogi (Hardcover)
4

2 回答 2

1

firstBlockSoup标签中获取标题会更容易:

>>> firstBlockSoup.attrs['data-item-name']
'Wilco Classic Library: Autobiography Of a Yogi (Hardcover)'
于 2013-05-04T21:54:33.743 回答
1

只需使用上的text方法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)
于 2013-05-04T22:17:26.930 回答