Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions dirhunt/crawler_url.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
import cgi
import socket
from email.message import Message

from bs4 import BeautifulSoup
from requests import RequestException
Expand All @@ -17,6 +17,14 @@
}


def parse_content_type(content_type):
if not content_type:
return ''
message = Message()
message['content-type'] = content_type
return message.get_content_type()


class CrawlerUrl(object):
def __init__(self, crawler, url, depth=3, source=None, exists=None, type=None, timeout=10):
"""
Expand Down Expand Up @@ -71,7 +79,7 @@ def start(self):
self.crawler.results.put(Error(self, e))
self.close()
return self
content_type = cgi.parse_header(resp.headers.get('Content-Type', ''))[0]
content_type = parse_content_type(resp.headers.get('Content-Type', ''))
soup = BeautifulSoup(text, 'html.parser') if content_type == 'text/html' else None
except RequestException as e:
self.crawler.current_processed_count += 1
Expand Down Expand Up @@ -112,7 +120,7 @@ def maybe_rewrite(self):
def must_be_downloaded(self, response):
"""The file must be downloaded to obtain information.
"""
return self.maybe_directory() or (cgi.parse_header(response.headers.get('Content-Type', ''))[0] in [
return self.maybe_directory() or (parse_content_type(response.headers.get('Content-Type', '')) in [
'text/css', 'application/javascript'
])

Expand Down
6 changes: 5 additions & 1 deletion dirhunt/tests/test_crawler_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@
import requests
import requests_mock

from dirhunt.crawler_url import CrawlerUrl
from dirhunt.crawler_url import CrawlerUrl, parse_content_type
from dirhunt.tests.base import CrawlerTestBase

from dirhunt.tests._compat import patch, Mock


class TestCrawlerUrl(CrawlerTestBase, unittest.TestCase):
def test_parse_content_type(self):
self.assertEqual(parse_content_type('text/html; charset=utf-8'), 'text/html')
self.assertEqual(parse_content_type(''), '')

def test_start(self):
crawler = self.get_crawler()
crawler.closing = False
Expand Down