搜索已解析网址的逻辑

时间:2015-03-23 03:17:45

标签: python

尝试创建网页抓取工具。获取MissingSchema:URL错误无效。

这是我的代码:

import requests
from bs4 import BeautifulSoup as bs

class HrefScraper(object):
def __init__(self,url):
    self.url = url

def requestUrl(self):
    getpage = requests.get(self.url)
    return getpage.content

def hrefParser(self):
        _list = []
        soup = bs(self.requestUrl())
        anchors = soup.findAll('a')      
        for items in anchors:
            href = items.get('href',None)
            if 'http' in href:
                if url[11:] in href and href not in _list:
                    _list.append(href)
            else:
                _list.append(href )
                if '//' in href and 'http' not in href:
                    _list.append(self.url+href)
        return _list


if __name__=='__main__':
    url = 'https://www.google.com'
    scraper = HrefScraper(url)
    scraper.requestUrl()
    scraper.hrefParser()
    for i in scraper.hrefParser():
        Loop=HrefScraper(i)
        Loop.requestUrl()
        try:
            for i in Loop.hrefParser():
                 print i
        except TypeError:
            pass

该脚本从网页中获取所有网址,然后以递归方式循环。至少是预期的影响。当脚本到达只包含没有站点地址的目录的Href标记时,它会很难失败。我试图为它创建处理但没有成功。有人可以帮我理解一个更好的方法来做到这一点。

我有办法吗?

url = request.headers ['host']; request.get(url + // randomSomethingWithNoAddress)

感谢您提供任何建议:)

编辑: 发布在我的帖子上方的重复链接不是我的问题的答案。我完全理解OP在说什么。我用“self.url + href”写了一个处理程序,所以不需要urljuoin。

我的问题是: 我开始得到这样的网址“http://www.example.com” 我崩溃了这样的“/政策”网址 为什么“/ policy”而不是“/ press /”。如果您运行脚本,您可以看到我在说什么。

我对脚本的理解是错误的吗?为什么我会得到这么多绝对路径而不会失败?

0 个答案:

没有答案