Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 网络爬虫程序错误:";AttributeError:Spider实例没有属性';查找'&引用;_Python_Web Crawler_Urlparse - Fatal编程技术网

Python 网络爬虫程序错误:";AttributeError:Spider实例没有属性';查找'&引用;

Python 网络爬虫程序错误:";AttributeError:Spider实例没有属性';查找'&引用;,python,web-crawler,urlparse,Python,Web Crawler,Urlparse,我的网络爬虫和python的urlparse插件有问题。我下面的代码基本上是爬网一个特定的域,比如bloomberg,并将所有html下载到我的桌面上。它仍处于相当早期的阶段,所以我相信您会注意到错误等(我是python新手) 我目前遇到的具体问题是与函数recostructure\u url有关。我已经分别测试了urlparse.urljoin(a,b)函数,它以我期望的方式运行,但在这个类中它就是不喜欢它。你们谁能告诉我这里有什么问题吗 如果在我的代码中有任何其他问题对您来说是显而易见的,请

我的网络爬虫和python的urlparse插件有问题。我下面的代码基本上是爬网一个特定的域,比如bloomberg,并将所有html下载到我的桌面上。它仍处于相当早期的阶段,所以我相信您会注意到错误等(我是python新手)

我目前遇到的具体问题是与函数
recostructure\u url
有关。我已经分别测试了
urlparse.urljoin(a,b)
函数,它以我期望的方式运行,但在这个类中它就是不喜欢它。你们谁能告诉我这里有什么问题吗

如果在我的代码中有任何其他问题对您来说是显而易见的,请随时大声说出,这是我第一次尝试编写完整的程序。尽管注意到这仍处于相对早期的阶段。非常感谢你的帮助

#note: <meta content='Story' property='bb:resource_type'>

import urllib2
import os
from bs4 import BeautifulSoup
from urlparse import urljoin

class Spider:

    links_to_crawl = []
    crawled_links = []
    ignored_links = ['/']
    domain = 'http://bloomberg.com/'
    #meta type = ('meta', {'property','bb:resource_type'})['content']=='Story'

    # append all starting link to links_to_crawl
    def __init__(self, url):
        print 'Spider initialising...'
        self.links_to_crawl.append(url)

    # open input url and return html
    def grab_html(self,url):
        open_url = self.urllib2.urlopen(url)
        data = open_url.read()
        open_url.close()
        return data

    # return title from input html for file naming and ensure
    # no '/' present in title.
    def get_title(self, data=''):
        title_start = data.find('<title>')+7
        title_end = data.find('</title>')-1
        title = data[title_start:title_end]
        title = title.translate(None, '/')
        return title+".txt"

    # return date from input html for file saving structure
    def get_date(self, data=''):
        soup = self.BeautifulSoup(data)
        # try statement to avoid error when meta tag combinations
        # not found.
        try:
            date = soup.find('meta', {'name':'pubdate'})['content']
            return date[:12] # !! only tested with bloomberg.com !!
        # if there is no published date, return 'Other'
        except TypeError:
            return 'Other'

    # if link is relative url return 'Rel' or 
    # if url is allowed domain return 'Abs', else False.
    def url_type(self,url=''):
        if url[0:4] != 'http':
            return 'Rel'
        elif url.find(self.domain) != -1:
            return 'Abs'
        else:
            return False

    # reconstruct relative url
    def reconstruct_url(self, page='', rel=''):
        print page #debug
        print rel #debug
        print self.urljoin(page, rel) #debug
        return self.urljoin(page, rel)

    # get all links in input html and append to links_to_crawl
    # unless in crawled_links or ignored_links
    # if link is relative url reconstruct url and append to 
    # links_to_crawl, append relative url to ignored_links
    def get_links(self, data=''):
        soup = self.BeautifulSoup(data) 
        for link in soup.find_all('a'):
            # try statement to avoid error when finding
            # <a> tags withou 'href'
            try:
                if link['href'] in self.ignored_links or self.crawled_links:
                    pass
                else:
                    if self.url_type(link['href'])=='Rel':
                        reconstructed_link = self.reconstruct_url(self.domain, link['href']) #to change !!!!!!!!!!!!!!!!!
                        self.links_to_crawl.append(reconstructed_link) # append reconstructed link to links_to_crawl
                        self.ignored_links.append(link['href']) # append original link to ignored_links
                    else:
                        self.links_to_crawl.append(link['href'])
            except KeyError:
                pass

    # if directory exists do nothing
    # if directory does not exist write directory
    def ensure_dir(self, directory=''):
        if self.os.path.exists(directory):
            pass
        else:
            self.os.makedirs(directory)

    # ensure the html being saved is the type requested
    # currently only compatible with 1 meta type
    def ensure_meta_type(self, data=''):
        soup = self.BeautifulSoup(data)
        try:
            soup.find('meta', {'property':'bb:resource_type'})['content']=='Story'
            print 'True'
            return True
        except TypeError:
            print 'False'
            return False

    # save input html to txt file on mac os desktop and return
    # absolute path to file
    def save_html(self,data=''):
        if self.ensure_meta_type(data):
            print 'SAVING URL'
            # allocate save path for file and ensure save path exists
            save_path = self.os.path.abspath('/Users/sampeka/Desktop/Python Spider'+'/'+self.get_date(data))
            self.ensure_dir(save_path)
            # get file name and write file to absolute path
            file_name = self.get_title(data)
            absolute_path = save_path+'/'+file_name
            opened_file = open(absolute_path,'w')
            opened_file.write(data)
            opened_file.close()
        else:
            pass



    # crawl links_to_crawl and pop to crawled_links list
    # if ValueError then pop to ignored_links
    # except urllib2.URLError to avoid web crawler crawling
    # non-url links  
    def crawl_links(self):
        while len(self.links_to_crawl) > 0:
            url = self.links_to_crawl[0]
            print url
            try:
                data = self.grab_html(url)
                self.get_links(data)
                self.save_html(data)
                self.crawled_links.append(self.links_to_crawl.pop(0))
            except (ValueError, self.urllib2.URLError):
                self.ignored_links.append(self.links_to_crawl.pop(0))
        print 'Spider finished.'
        print 'Ignored links:'
        print self.ignored_links
        print 'Crawled links:'
        print self.crawled_links


spider = Spider('http://www.bloomberg.com/news')
spider.crawl_links()    
#注意:
导入urllib2
导入操作系统
从bs4导入BeautifulSoup
从urlparse导入urljoin
类蜘蛛:
链接到爬网=[]
爬网链接=[]
忽略链接=['/']
域http://bloomberg.com/'
#元类型=('meta',{'property','bb:resource_type'})['content']='Story'
#将所有起始链接附加到链接\u到\u爬网
定义初始化(self,url):
打印“蜘蛛初始化…”
self.links\u to\u crawl.append(url)
#打开输入url并返回html
def抓取_html(自我,url):
open_url=self.urllib2.urlopen(url)
data=open_url.read()
open_url.close()
返回数据
#从输入html返回文件命名的标题,并确保
#标题中不存在“/”。
def get_标题(自身,数据=“”):
title_start=data.find(“”)+7
title_end=data.find(“”)-1
title=数据[title\u开始:title\u结束]
title=title.translate(无“/”)
返回标题+“.txt”
#文件保存结构的输入html返回日期
def get_日期(自身,数据=“”):
soup=self.BeautifulSoup(数据)
#try语句避免元标记组合时出错
#没有找到。
尝试:
date=soup.find('meta',{'name':'pubdate'})['content']
返回日期[:12]#!!仅在bloomberg.com上测试!!
#如果没有发布日期,请返回“其他”
除类型错误外:
返回“其他”
#如果链接是相对url,则返回“Rel”或
#如果允许url,域返回“Abs”,否则为False。
def url_类型(自身,url=''):
如果url[0:4]!='http':
返回'Rel'
elif url.find(self.domain)!=-1:
返回“Abs”
其他:
返回错误
#重建相对url
定义url(self,page='',rel=''):
打印页面#调试
打印相关调试
打印self.urljoin(第页,rel)#调试
返回self.urljoin(第页,rel)
#获取输入html中的所有链接并附加到链接
#除非在爬网链接或忽略链接中
#如果链接是相对url,则重构url并附加到
#链接到爬网,将相对url附加到被忽略的链接
def get_链接(自身,数据=“”):
soup=self.BeautifulSoup(数据)
查找所有('a'):
#try语句以避免查找时出错
#带有“href”的标记
尝试:
如果self.ignored_链接或self.crawled_链接中的链接['href']:
通过
其他:
如果self.url_type(link['href'])='Rel':
重建链接=self。重建url(self.domain,link['href'])#更改!!!!!!!!!!!!!!!!!
self.links_to_crawl.append(重建链接)#append重建链接to links_to_crawl
self.ignored_links.append(link['href'])#将原始链接附加到已忽略的_链接
其他:
self.links\u to\u crawl.append(link['href'])
除KeyError外:
通过
#如果目录存在,则不执行任何操作
#如果目录不存在,则写入目录
def sure_dir(self,directory=''):
如果self.os.path.存在(目录):
通过
其他:
self.os.makedirs(目录)
#确保保存的html是请求的类型
#当前仅与1个元类型兼容
def确保元类型(自身,数据=“”):
soup=self.BeautifulSoup(数据)
尝试:
soup.find('meta',{'property':'bb:resource_type'})['content']=='Story'
打印“真”
返回真值
除类型错误外:
打印“假”
返回错误
#将输入html保存到mac os桌面上的txt文件并返回
#文件的绝对路径
def save_html(自身,数据=“”):
如果是自确认元类型(数据):
打印“保存URL”
#为文件分配保存路径并确保保存路径存在
save_path=self.os.path.abspath('/Users/sampeka/Desktop/Python Spider'+'/'+self.get_date(data))
self.sure\u dir(保存路径)
#获取文件名并将文件写入绝对路径
文件名=self.get\u标题(数据)
绝对路径=保存路径+'/'+文件名
opened_file=open(绝对路径,'w')
打开的_文件。写入(数据)
已打开\u文件。关闭()
其他:
通过
#爬网链接\u到\u爬网并弹出到爬网链接列表
#如果ValueError,则弹出被忽略的链接
#除了urllib2.URLError以避免网络爬虫爬行
#非url链接
def爬网链接(自):
而len(自链接到爬网)>0:
url=self.links\u-to\u-crawl[0]
打印url
尝试:
data=self.grab\u html(url)
self.get_链接(数据)
self.save_html(数据)
self.crawled_links.append(self.links_to_crawl.pop(0))
除了(ValueError,self.urllib2.urleror):
self.u链接
# reconstruct relative url
def reconstruct_url(self, page='', rel=''):
    print page #debug
    print rel #debug
    print urljoin(page, rel) #debug
    return urljoin(page, rel)