【问题标题】:Extract HTML Links using Python使用 Python 提取 HTML 链接
【发布时间】:2014-05-19 22:13:37
【问题描述】:

我正在尝试使用 Python 提取给定一组网站的 iframe src。例如,我的输入将是 A.com、B.com、C.com,如果这些网站中的每一个都有链接到 D.com、E.com、F.com 的 iframe,(如果网站没有,则为“无”有一个 iframe)然后我希望输出是以下形式:

Site    Iframe Src
A.com    D.com
B.com    E.com
C.com    F.com

目前,我有这样的事情:

from collections import defaultdict
import urllib2
import re

 def PrintLinks(website):
 counter = 0
 regexp_link= regexp_link = r'''<frame src =((http|ftp)s?://.*?)'''
 pattern = re.compile(regexp_link)
 links = [None]*len(website)
 for x in website:
     html_page = urllib2.urlopen(website[counter])
     html = html_page.read()
     links[counter] = re.findall(pattern,html)
     counter += 1
 return links

def main():
 website=["A.com","B.com","C.com"]

这是最好的方法吗?如何让输出成为我想要的格式?谢谢!

【问题讨论】:

    标签: python html arrays list iframe


    【解决方案1】:

    您不需要使用正则表达式重新发明轮子,有很棒的 python 包可以为您做到这一点,可能是最著名的 BeautifulSoup。

    用pip安装BeautifulSouphttplib2,试试这个


    import httplib2
    from BeautifulSoup import BeautifulSoup, SoupStrainer
    
    sites=['http://www.site1.com', 'http://www.site2.com', 'http://www.site3.com']
    http = httplib2.Http()
    
    for site in sites:
        status, response = http.request(site)
        for iframe in BeautifulSoup(response, parseOnlyThese=SoupStrainer('iframe')):
            print site + ' ' + iframe['src']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 2013-08-29
      • 2012-07-07
      • 2021-11-03
      • 2018-12-25
      • 2020-10-04
      相关资源
      最近更新 更多