【发布时间】:2013-05-13 18:11:53
【问题描述】:
首先,我对 Python 还是很陌生。我正在尝试从离线网站上抓取联系信息并将信息输出到 csv。我想获取页面 url(不确定如何从 html 中执行此操作)、电子邮件、电话、位置数据(如果可能)、任何名称、任何电话号码以及 html 站点的标语行(如果存在)。
更新 #2 代码:
import os, csv, re
from bs4 import BeautifulSoup
topdir = 'C:\\projects\\training\\html'
output = csv.writer(open("scrape.csv", "wb+"))
output.writerow(["headline", "name", "email", "phone", "location", "url"])
all_contacts = []
for root, dirs, files in os.walk(topdir):
for f in files:
if f.lower().endswith((".html", ".htm")):
soup = BeautifulSoup(f)
def mailto_link(soup):
if soup.name != 'a':
return None
for key, value in soup.attrs:
if key == 'href':
m = re.search('mailto:(.*)',value)
if m:
all_contacts.append(m)
return m.group(1)
return None
for ul in soup.findAll('ul'):
contact = []
for li in soup.findAll('li'):
s = li.find('span')
if not (s and s.string):
continue
if s.string == 'Email:':
a = li.find(mailto_link)
if a:
contact['email'] = mailto_link(a)
elif s.string == 'Website:':
a = li.find('a')
if a:
contact['website'] = a['href']
elif s.string == 'Phone:':
contact['phone'] = unicode(s.nextSibling).strip()
all_contacts.append(contact)
output.writerow([all_contacts])
print "Finished"
此输出当前不返回除行标题以外的任何内容。我在这里想念什么?这应该至少从 html 文件返回一些信息,也就是这个页面:http://bendoeslife.tumblr.com/about
【问题讨论】:
-
你通常不能从页面HTML中获取页面URL;您需要在获取时保存它。至于其余的……我们需要查看一些示例数据来告诉您解析器出了什么问题。
标签: python html csv web-scraping beautifulsoup