猫史档案馆


【Python作品分享】高级爬虫【作品秀】

用户:jerrydyxjerrydyx查看:0 回复:5 评论:0 创建时间:2019-08-13T18:25:22


【作品展示】

center_image

 

【作品介绍】

---------------------

版权声明:本文为CSDN博主「完美风暴4」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。

原文链接喵jsqfengbao/article/details/60875081

 

【作品源代码】

import re
import urlparse
import urllib2
import time
from datetime import datetime
import robotparser
import Queue
from scrape_callback3 import ScrapeCallback


def link_crawler(seed_url, link_regex=None, delay=5, max_depth=-1, max_urls=-1, headers=None, user_agent='wswp',
                 proxy=None, num_retries=1, scrape_callback=None):
    """Crawl from the given seed URL following links matched by link_regex
    """
    # the queue of URL's that still need to be crawled
    crawl_queue = [seed_url]
    # the URL's that have been seen and at what depth
    seen = {seed_url: 0}
    # track how many URL's have been downloaded
    num_urls = 0
    rp = get_robots(seed_url)
    throttle = Throttle(delay)
    headers = headers or {}
    if user_agent:
        headers['User-agent'] = user_agent

    while crawl_queue:
        url = crawl_queue.pop()
        depth = seen[url]
        # check url passes robots.txt restrictions
        if rp.can_fetch(user_agent, url):
            throttle.wait(url)
            html = download(url, headers, proxy=proxy, num_retries=num_retries)
            links = []
            if scrape_callback:
                links.extend(scrape_callback(url, html) or [])

            if depth != max_depth:
                # can still crawl further
                if link_regex:
                    # filter for links matching our regular expression
                    links.extend(link for link in get_links(html) if re.match(link_regex, link))

                for link in links:
                    link = normalize(seed_url, link)
                    # check whether already crawled this link
                    if link not in seen:
                        seen[link] = depth + 1
                        # check link is within same domain
                        if same_domain(seed_url, link):
                            # success! add this new link to queue
                            crawl_queue.append(link)

            # check whether have reached downloaded maximum
            num_urls += 1
            if num_urls == max_urls:
                break
        else:
            print 'Blocked by robots.txt:', url


class Throttle:
    """Throttle downloading by sleeping between requests to same domain
    """

    def __init__(self, delay):
        # amount of delay between downloads for each domain
        self.delay = delay
        # timestamp of when a domain was last accessed
        self.domains = {}

    def wait(self, url):
        """Delay if have accessed this domain recently
        """
        domain = urlparse.urlsplit(url).netloc
        last_accessed = self.domains.get(domain)
        if self.delay > 0 and last_accessed is not None:
            sleep_secs = self.delay - (datetime.now() - last_accessed).seconds
            if sleep_secs > 0:
                time.sleep(sleep_secs)
        self.domains[domain] = datetime.now()


def download(url, headers, proxy, num_retries, data=None):
    print 'Downloading:', url
    request = urllib2.Request(url, data, headers)
    opener = urllib2.build_opener()
    if proxy:
        proxy_params = {urlparse.urlparse(url).scheme: proxy}
        opener.add_handler(urllib2.ProxyHandler(proxy_params))
    try:
        response = opener.open(request)
        html = response.read()
        code = response.code
    except urllib2.URLError as e:
        print 'Download error:', e.reason
        html = ''
        if hasattr(e, 'code'):
            code = e.code
            if num_retries > 0 and 500 <= code < 600:
                # retry 5XX HTTP errors
                html = download(url, headers, proxy, num_retries - 1, data)
        else:
            code = None
    return html


def normalize(seed_url, link):
    """Normalize this URL by removing hash and adding domain
    """
    link, _ = urlparse.urldefrag(link)  # remove hash to avoid duplicates
    return urlparse.urljoin(seed_url, link)


def same_domain(url1, url2):
    """Return True if both URL's belong to same domain
    """
    return urlparse.urlparse(url1).netloc == urlparse.urlparse(url2).netloc


def get_robots(url):
    """Initialize robots parser for this domain
    """
    rp = robotparser.RobotFileParser()
    rp.set_url(urlparse.urljoin(url, '/robots.txt'))
    rp.read()
    return rp


def get_links(html):
    """Return a list of links from html
    """
    # a regular expression to extract all links from the webpage
    webpage_regex = re.compile(']+href=["\'](.*?)["\']', re.IGNORECASE)
    # list of all links from the webpage
    return webpage_regex.findall(html)


if __name__ == '__main__':
    # link_crawle喵 '/(index|view)', delay=0, num_retries=1, user_agent='BadCrawler')
    # link_crawle喵 '/(index|view)', delay=0, num_retries=1, max_depth=1,
    #              user_agent='GoodCrawler')
    link_crawler('http://fund.eastmoney.com',r'/fund.html#os_0;isall_0;ft_;pt_1',max_depth=-1,scrape_callback=ScrapeCallback

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 1下一页
已退坑已退坑

我还以为是你写的

点赞0


评论


Hello_WorldHello_World

这个爬完在哪啊

点赞0


评论


KennethYKennethY

import json

from gevent import spawn, joinall, sleep
from gevent.monkey import patch_all

# from time import time

patch_all()

from lxml.etree import H喵L
from requests import get

essential_url = "https://book.qidian.com/ajax/book/category?_csrfToken=4OOjTKDQmX2MWa9fWTPnLAbNv9AOExG52nPBlAse&bookId=1003553070"
directory = []
essential_url_list = []
content = []
# time_sky = []
allocation_url = [[], [], [], [], [], [], [], [], [], []]
task_list = []


# 创建小说目录与url列表
def extraction_url(essential_url):
    response = get(url=essential_url)
    response.encoding = "utf-8"
    url_get = response.text
    myjson = json.loads(url_get)
    novel_chapter = myjson.get("data").get("vs")

    # 创建小说目录列表
    for novel_chapter_for in novel_chapter:
        chapter_name = novel_chapter_for.get("vN")
        content = novel_chapter_for.get("cs")
        chapter_list = []
        for content_for in content:
            chapter = {content_for.get("cN"): content_for.get("cU")}
            chapter_list.append(chapter)
            # 创建url列表
            essential_url_list.append("https://read.qidian.com/chapter/" + content_for.get("cU"))
        directory.append({chapter_name: chapter_list})


# 获取小说内容
def response(url_list):
    for url_list_for in url_list:
        # print(url_list_for)
        url_list_get = get(url_list_for).text
        text = H喵L(url_list_get).xpath('//div[@class="main-text-wrap"]/div[2]/p/text()')
        content.append(text)
        print(text)
        sleep(1)


def main():
    print('Start the crawler!!!\n--------------------')
    extraction_url(essential_url=essential_url)

    # 分配url
    num = 0
    for url_list_for in essential_url_list:
        if num == 10:
            num = 0
        allocation_url[num].append(url_list_for)
        num += 1

    print(allocation_url)

    # 创建协程任务列表
    for allocation_url_for in range(len(allocation_url)):
        task_list.append(spawn(response, allocation_url[allocation_url_for]))

    # 开始协程
    joinall(task_list)


if __name__ == '__main__':
    main()

点赞0


评论


dounsm36dounsm36

自动把"h t m l "中的"t m"改成了"喵"

点赞0


评论


ABS寄予清风NotFoundABS寄予清风NotFound

import re
import urlparse
import urllib2
import time
from datetime import datetime
import robotparser
import Queue
from scrape_callback3 import ScrapeCallback


def link_crawler(seed_url, link_regex=None, delay=5, max_depth=-1, max_urls=-1, headers=None, user_agent='wswp',
                 proxy=None, num_retries=1, scrape_callback=None):
    """Crawl from the given seed URL following links matched by link_regex
    """
    # the queue of URL's that still need to be crawled
    crawl_queue = [seed_url]
    # the URL's that have been seen and at what depth
    seen = {seed_url: 0}
    # track how many URL's have been downloaded
    num_urls = 0
    rp = get_robots(seed_url)
    throttle = Throttle(delay)
    headers = headers or {}
    if user_agent:
        headers['User-agent'] = user_agent

    while crawl_queue:
        url = crawl_queue.pop()
        depth = seen[url]
        # check url passes robots.txt restrictions
        if rp.can_fetch(user_agent, url):
            throttle.wait(url)
            h喵l = download(url, headers, proxy=proxy, num_retries=num_retries)
            links = []
            if scrape_callback:
                links.extend(scrape_callback(url, h喵l) or [])

            if depth != max_depth:
                # can still crawl further
                if link_regex:
                    # filter for links matching our regular expression
                    links.extend(link for link in get_links(h喵l) if re.match(link_regex, link))

                for link in links:
                    link = normalize(seed_url, link)
                    # check whether already crawled this link
                    if link not in seen:
                        seen[link] = depth + 1
                        # check link is within same domain
                        if same_domain(seed_url, link):
                            # success! add this new link to queue
                            crawl_queue.append(link)

            # check whether have reached downloaded maximum
            num_urls += 1
            if num_urls == max_urls:
                break
        else:
            print 'Blocked by robots.txt:', url


class Throttle:
    """Throttle downloading by sleeping between requests to same domain
    """

    def __init__(self, delay):
        # amount of delay between downloads for each domain
        self.delay = delay
        # timestamp of when a domain was last accessed
        self.domains = {}

    def wait(self, url):
        """Delay if have accessed this domain recently
        """
        domain = urlparse.urlsplit(url).netloc
        last_accessed = self.domains.get(domain)
        if self.delay > 0 and last_accessed is not None:
            sleep_secs = self.delay - (datetime.now() - last_accessed).seconds
            if sleep_secs > 0:
                time.sleep(sleep_secs)
        self.domains[domain] = datetime.now()


def download(url, headers, proxy, num_retries, data=None):
    print 'Downloading:', url
    request = urllib2.Request(url, data, headers)
    opener = urllib2.build_opener()
    if proxy:
        proxy_params = {urlparse.urlparse(url).scheme: proxy}
        opener.add_handler(urllib2.ProxyHandler(proxy_params))
    try:
        response = opener.open(request)
        h喵l = response.read()
        code = response.code
    except urllib2.URLError as e:
        print 'Download error:', e.reason
        h喵l = ''
        if hasattr(e, 'code'):
            code = e.code
            if num_retries > 0 and 500 <= code < 600:
                # retry 5XX HTTP errors
                h喵l = download(url, headers, proxy, num_retries - 1, data)
        else:
            code = None
    return h喵l


def normalize(seed_url, link):
    """Normalize this URL by removing hash and adding domain
    """
    link, _ = urlparse.urldefrag(link)  # remove hash to avoid duplicates
    return urlparse.ur喵oin(seed_url, link)


def same_domain(url1, url2):
    """Return True if both URL's belong to same domain
    """
    return urlparse.urlparse(url1).netloc == urlparse.urlparse(url2).netloc


def get_robots(url):
    """Initialize robots parser for this domain
    """
    rp = robotparser.RobotFileParser()
    rp.set_url(urlparse.ur喵oin(url, '/robots.txt'))
    rp.read()
    return rp


def get_links(h喵l):
    """Return a list of links from h喵l
    """
    # a regular expression to extract all links from the webpage
    webpage_regex = re.compile(']+href=["\'](.*?)["\']', re.IGNORECASE)
    # list of all links from the webpage
    return webpage_regex.findall(h喵l)


if __name__ == '__main__':
    # link_crawler('http://example.webscraping.com', '/(index|view)', delay=0, num_retries=1, user_agent='BadCrawler')
    # link_crawler('http://example.webscraping.com', '/(index|view)', delay=0, num_retries=1, max_depth=1,
    #              user_agent='GoodCrawler')
    link_crawler('http://fund.eas喵oney.com',r'/fund.h喵l#os_0;isall_0;ft_;pt_1',max_depth=-1,scrape_callback=ScrapeCallback

 

点赞0


评论