从字符串中提取信息

时间:2014-11-27 05:22:18

标签: python html regex beautifulsoup html-parsing

以下代码正常运行,但我无法提取所需的信息。 我可以使用Soup还是需要正则表达式?

from bs4 import BeautifulSoup
import urllib2
mynumber='1234567890'
url="http://www.nccptrai.gov.in/nccpregistry/saveSearchSub.misc?phoneno="+mynumber
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())   

table = soup.findAll("table")[1]
myl=[item.text.strip() for item in table.find_all('td')] 
import re
re.findall(r'is:\s*[^,]*' , myl[1])

预期输出是第一个切片的第一个字符串中提到的4个参数。

['2014-08-07 15:50:00', 'Andhra Pradesh', 'Unitech', '0']

(注意日期更改为Y-M-D)

返回的字符串看起来像这样...

[u'is:\n 31-10-2009 01:11\n\n\nService Area : \n Mumbai\n\n\nService Provider :\n Idea\n\n\n\n\n\nYour Preference is :0']

1 个答案:

答案 0 :(得分:1)

我依赖The number is registered in NCPR标题(它位于td标记中,类GridHeader)并通过find_next_siblings()获取下一行:

import urllib2
from bs4 import BeautifulSoup

mynumber = '1234567890'
url = "http://www.nccptrai.gov.in/nccpregistry/saveSearchSub.misc?phoneno=" + mynumber

soup = BeautifulSoup(urllib2.urlopen(url))

header = soup.find('td', class_='GridHeader')

result = []
for row in header.parent.find_next_siblings('tr'):
    cells = row.find_all('td')
    try:
        result.append(cells[2].get_text(strip=True))
    except IndexError:
        continue
print result

打印:

[u'07-08-2014 15:50', u'Andhra Pradesh', u'Unitech', u'0']