【问题标题】:simple web crawler简单的网络爬虫
【发布时间】:2023-03-13 07:24:02
【问题描述】:

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

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/')

【问题讨论】:

  • 你能发布完整的回溯吗?这至少应该缩小对 None 值进行的函数调用。

标签: python-2.7 beautifulsoup


【解决方案1】:

[UPDATE]这是完整的项目代码

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

[ANWSER]

soup('a') 返回完整的 html 标签。

<a href="http://itunes.apple.com/us/store">Buy Music Now</a>

所以 urlopen 给出了错误 'NoneType' 对象不可调用'。您只需要提取 url/href。

links=soup.findAll('a',href=True)
for l in links:
    print(l['href'])

您也需要验证 url。参考以下 anwsers

我再次建议您使用 python 集合代替 Arrays。您可以轻松添加、省略重复的 url。

试试下面的代码:

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/')

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 2016-06-23
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2015-06-26
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多