从输出中只提取几行

时间:2014-10-25 08:49:54

标签: python beautifulsoup

以下代码按预期工作。它返回7行。

from bs4 import BeautifulSoup
import urllib2
url="http://www.findandtrace.com/trace-mobile-number-location?mobilenumber=9834900000&submit=Trace"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
universities=soup.findAll('b')
for eachuniversity in universities:
   print eachuniversity.string

但我只需要第3和第4行。

9834900000
9834900000
MADHYA PRADESH & CHHATISGARH 
AIRTEL
GSM
 LIVE - Active 
Mobile Reputation & Monitoring 

预期输出是一个元组:

(' MADHYA PRADESH& CHHATIS​​GARH',' AIRTEL')

我如何实现这一结果?

1 个答案:

答案 0 :(得分:3)

不要查找粗体标签,而是查找表并解析行:

data = {}
for row in soup.select('#content #table .row'):
    key, value = (cell.text for cell in row.select('.cell'))
    data[key.rstrip(' :')] = value.strip()

这会产生:

{u'Connection Status': u'LIVE - Active',
 u'Mobile Phone': u'9834900000',
 u'Network Operator / Service Provider': u'AIRTEL',
 u'Service Type / Signal': u'GSM',
 u'Telecom Circle / State': u'MADHYA PRADESH & CHHATISGARH'}

允许您通过键而不是索引来提取所需的数据:

data['Telecom Circle / State'], data['Network Operator / Service Provider']