只从outpu提取几行

2024-09-29 08:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码按预期工作。它返回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

但我只需要第三和第四条线。你知道吗

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

预期输出为元组:

('MADHYA PRADESH&CHHATISGARH','AIRTEL')

我如何达到这个结果?你知道吗


Tags: 代码fromimporturlpageurllib2soupbs4
1条回答
网友
1楼 · 发布于 2024-09-29 08:25:25

与其查找粗体标记,不如查找表并解析出行:

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

相关问题 更多 >