【问题标题】:extract contact information from html with python使用python从html中提取联系信息
【发布时间】:2015-04-14 22:39:09
【问题描述】:

这是一个示例 html

<div class="yui3-u-5-6" id="browse-products">
<div id="kazbah-contact">
  <span class="contact-info-title">Contact 00Nothing:</span>
  <a href="mailto:info@00nothing.com">info@00nothing.com</a> | 800-410-2074
   | C/O Score X Score
    &nbsp;8118-D Statesville Rd
    ,
  Charlotte,
  NC
  28269
</div>
<div class="clearfix"></div>

我想在这里提取联系信息,电子邮件、电话和地址。 我应该如何用 python 做到这一点?谢谢

【问题讨论】:

  • @RafaelCardoso 我读到了。但是我怎样才能得到“|”之后的信息呢?我的意思是,获取 info@00nothing.com 很容易,但获取电话和地址却很难
  • 也许split 的文档会告诉你如何提取那些“硬”部分。此外,请考虑将来如果您展示您自己尝试过的某种形式的代码,您将获得(更好的)答案。如果您特别写到获取电子邮件地址很容易,那么您为什么不复制您在问题中使用的代码?查看writing the perfect questionhow to ask

标签: python extract


【解决方案1】:

我用这段代码来提取信息

# _*_ coding:utf-8 _*_
import urllib2
import urllib
import re
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def grabHref(url,localfile):
    html = urllib2.urlopen(url).read()
    html = unicode(html,'gb2312','ignore').encode('utf-8','ignore')
    soup = BeautifulSoup(html)
    myfile = open(localfile,'wb')
    for link in soup.select("div >            a[href^=http://www.karmaloop.com/kazbah/browse]"):
        for item in BeautifulSoup(urllib2.urlopen(link['href']).read()).select("div > a[href^=mailto]"):
            contactInfo = item.get_text()
            print link['href']
            print contactInfo

        myfile.write(link['href'])
        myfile.write('\r\n')
        myfile.write(contactInfo)
        myfile.write('\r\n')
    myfile.close()



def main():
    url = "http://www.karmaloop.com/brands"
    localfile = 'Contact.txt'
    grabHref(url,localfile)
if __name__=="__main__":
    main()

但是我这里还是只能获取邮箱地址,怎么获取电话号码和地址呢?谢谢

【讨论】:

  • 我现在就明白了。但是对于 css 选择器,“div > a[href^=mailto]”可能不存在。如果找不到“div > a[href^=mailto]”我想继续,我该怎么办?
  • 我写 if BeautifulSoup(urllib2.urlopen(link['href']).read()).select("div > div[id^=kazbah-contact]") == False:继续,但它不起作用
  • 欢迎来到 Stack Overflow。这不是一个答案。您应该编辑原始问题以包含新信息,或者打开一个单独的问题。
猜你喜欢
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多