首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >简易网络爬虫

简易网络爬虫
EN

Stack Overflow用户
提问于 2012-12-01 11:15:19
回答 1查看 10.7K关注 0票数 1

我在python中为非常简单的网络爬虫编写了下面的程序,但是当我运行它时,它会返回'NoneType‘对象是不可调用的,您能帮我吗?

代码语言:javascript
运行
复制
import BeautifulSoup
import urllib2
def union(p,q):
    for e in q:
        if e not in p:
            p.append(e)

def crawler(SeedUrl):
    tocrawl=[SeedUrl]
    crawled=[]
    while tocrawl:
        page=tocrawl.pop()
        pagesource=urllib2.urlopen(page)
        s=pagesource.read()
        soup=BeautifulSoup.BeautifulSoup(s)
        links=soup('a')        
        if page not in crawled:
            union(tocrawl,links)
            crawled.append(page)

    return crawled
crawler('http://www.princeton.edu/main/')
EN

回答 1

Stack Overflow用户

发布于 2013-02-05 04:35:01

更新这里是完整的项目代码

https://bitbucket.org/deshan/simple-web-crawler

ANWSER

complete (‘a’)返回完整的html标记。

代码语言:javascript
运行
复制
<a href="http://itunes.apple.com/us/store">Buy Music Now</a>

因此,urlopen给出了错误'NoneType‘对象是不可调用的。您需要提取唯一的url/href。

代码语言:javascript
运行
复制
links=soup.findAll('a',href=True)
for l in links:
    print(l['href'])

您需要验证url too.refer到下面的解析器

我想再次建议您使用python来代替Arrays.you可以轻松地添加、删除重复的urls。

  • http://docs.python.org/2/library/sets.html

尝试以下代码:

代码语言:javascript
运行
复制
import re
import httplib
import urllib2
from urlparse import urlparse
import BeautifulSoup

regex = re.compile(
        r'^(?:http|ftp)s?://' # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
        r'localhost|' #localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
        r'(?::\d+)?' # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)

def isValidUrl(url):
    if regex.match(url) is not None:
        return True;
    return False

def crawler(SeedUrl):
    tocrawl=[SeedUrl]
    crawled=[]
    while tocrawl:
        page=tocrawl.pop()
        print 'Crawled:'+page
        pagesource=urllib2.urlopen(page)
        s=pagesource.read()
        soup=BeautifulSoup.BeautifulSoup(s)
        links=soup.findAll('a',href=True)        
        if page not in crawled:
            for l in links:
                if isValidUrl(l['href']):
                    tocrawl.append(l['href'])
            crawled.append(page)   
    return crawled
crawler('http://www.princeton.edu/main/')
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13658863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档