使用python从站点提取数据
我正在制作一个程序,从中提取数据 我编写了以下代码:使用python从站点提取数据,python,python-2.7,beautifulsoup,Python,Python 2.7,Beautifulsoup,我正在制作一个程序,从中提取数据 我编写了以下代码: def split_line(text): words = text.split() i = 0 details = '' while ((words[i] !='Contact')) and (i<len(words)): i=i+1 if(words[i] == 'Contact:'): break while ((words[i] !
def split_line(text):
words = text.split()
i = 0
details = ''
while ((words[i] !='Contact')) and (i<len(words)):
i=i+1
if(words[i] == 'Contact:'):
break
while ((words[i] !='Purpose')) and (i<len(words)):
if (words[i] == 'Purpose:'):
break
details = details+words[i]+' '
i=i+1
print(details)
def get_ngo_detail(ngo_url):
html=urlopen(ngo_url).read()
soup = BeautifulSoup(html)
table = soup.find('table', {'class': 'border3'})
td = soup.find('td', {'class': 'border'})
split_line(td.text)
def get_ngo_names(gujrat_url):
html = urlopen(gujrat_url).read()
soup = BeautifulSoup(html)
for link in soup.findAll('div',{'id':'mainbox'}):
for text in link.find_all('a'):
print(text.get_text())
ngo_link = 'http://www.gujarat.ngosindia.com/'+text.get('href')
get_ngo_detail(ngo_link)
#NGO_name = text2.get_text())
a = get_ngo_names(BASE_URL)
print a
def分割线(文本):
words=text.split()
i=0
详细信息=“”
虽然((words[i]!='Contact'))和(i尝试更好地拆分NGO站点的内容,但您可以给“split”方法一个正则表达式来拆分。
e、 g.“[联系人]+[电子邮件]+[电话号码]+[网站]+[目的]+[联系人]
我的正则表达式可能是错误的,但这是您应该朝的方向。您的分割线可以改进。假设您有以下文本:
s = """Add: 3rd Floor Khemha House
Drive in Road, Opp Drive in Cinema
Ahmedabad - 380 054
Gujarat
Tel: 91-79-7457611 , 79-7450378
Email: a.mitra1@lse.ac.uk
Website: http://www.aavishkaar.org
Contact: Angha Mitra
Purpose: Economics and Finance, Micro-enterprises
Aim/Objective/Mission: To provide timely financing, management support and professional expertise ..."""
现在,我们可以使用s.split(“\n”)
(在每一新行上拆分)将其转换为行,给出一个列表,其中每个项目都是一行:
lines = s.split("\n")
lines == ['Add: 3rd Floor Khemha House',
'Drive in Road, Opp Drive in Cinema',
...]
我们可以定义要提取的元素列表,以及保存结果的字典:
targets = ["Contact", "Purpose", "Email"]
results = {}
完成每一行,获取我们想要的信息:
for line in lines:
l = line.split(":")
if l[0] in targets:
results[l[0]] = l[1]
这给了我:
results == {'Contact': ' Angha Mitra',
'Purpose': ' Economics and Finance, Micro-enterprises',
'Email': ' a.mitra1@lse.ac.uk'}
作为找到解决方案的第一步,试着加入几个print()要验证数据是否正确/您在所有情况下的期望值…或使用pdb进入代码。使用您的代码查看网站上的整个列表,我会获得前6个列表的详细信息,但之后会得到空白结果。某些页面缺少数据,例如没有“网站”“。这是意料之中的。我知道其中一些会丢失一些数据,但为什么其他数据不会出现?我不知道,您必须输入一些print
,以了解您正在获取的内容以及如何处理它。