diff --git a/scrapy/link.py b/scrapy/link.py index 8bdcce761..dc6e64adc 100644 --- a/scrapy/link.py +++ b/scrapy/link.py @@ -4,8 +4,8 @@ This module defines the Link object used in Link extractors. For actual link extractors implementation see scrapy.linkextractors, or its documentation in: docs/topics/link-extractors.rst """ +from scrapy.utils.python import to_native_str -import six class Link(object): """Link objects represent an extracted link by the LinkExtractor.""" @@ -13,11 +13,10 @@ class Link(object): __slots__ = ['url', 'text', 'fragment', 'nofollow'] def __init__(self, url, text='', fragment='', nofollow=False): - if isinstance(url, six.text_type): + if not isinstance(url, str): import warnings - warnings.warn("Do not instantiate Link objects with unicode urls. " - "Assuming utf-8 encoding (which could be wrong)") - url = url.encode('utf-8') + warnings.warn("Link urls must be str objects.") + url = to_native_str(url) self.url = url self.text = text self.fragment = fragment diff --git a/scrapy/linkextractors/__init__.py b/scrapy/linkextractors/__init__.py index bb799e572..64efa0c55 100644 --- a/scrapy/linkextractors/__init__.py +++ b/scrapy/linkextractors/__init__.py @@ -39,7 +39,7 @@ IGNORED_EXTENSIONS = [ _re_type = type(re.compile("", 0)) _matches = lambda url, regexs: any((r.search(url) for r in regexs)) -_is_valid_url = lambda url: url.split('://', 1)[0] in set(['http', 'https', 'file']) +_is_valid_url = lambda url: url.split('://', 1)[0] in {'http', 'https', 'file'} class FilteringLinkExtractor(object): @@ -51,8 +51,10 @@ class FilteringLinkExtractor(object): self.link_extractor = link_extractor - self.allow_res = [x if isinstance(x, _re_type) else re.compile(x) for x in arg_to_iter(allow)] - self.deny_res = [x if isinstance(x, _re_type) else re.compile(x) for x in arg_to_iter(deny)] + self.allow_res = [x if isinstance(x, _re_type) else re.compile(x) + for x in arg_to_iter(allow)] + self.deny_res = [x if isinstance(x, _re_type) else re.compile(x) + for x in arg_to_iter(deny)] self.allow_domains = set(arg_to_iter(allow_domains)) self.deny_domains = set(arg_to_iter(deny_domains)) @@ -64,7 +66,7 @@ class FilteringLinkExtractor(object): self.canonicalize = canonicalize if deny_extensions is None: deny_extensions = IGNORED_EXTENSIONS - self.deny_extensions = set(['.' + e for e in arg_to_iter(deny_extensions)]) + self.deny_extensions = {'.' + e for e in arg_to_iter(deny_extensions)} def _link_allowed(self, link): if not _is_valid_url(link.url): @@ -104,5 +106,6 @@ class FilteringLinkExtractor(object): def _extract_links(self, *args, **kwargs): return self.link_extractor._extract_links(*args, **kwargs) + # Top-level imports from .lxmlhtml import LxmlLinkExtractor as LinkExtractor diff --git a/scrapy/linkextractors/lxmlhtml.py b/scrapy/linkextractors/lxmlhtml.py index e9fa521f3..e39c9950e 100644 --- a/scrapy/linkextractors/lxmlhtml.py +++ b/scrapy/linkextractors/lxmlhtml.py @@ -1,16 +1,14 @@ """ Link extractor based on lxml.html """ - -import re +import six from six.moves.urllib.parse import urlparse, urljoin import lxml.etree as etree -from scrapy.selector import Selector from scrapy.link import Link from scrapy.utils.misc import arg_to_iter -from scrapy.utils.python import unique as unique_list +from scrapy.utils.python import unique as unique_list, to_native_str from scrapy.linkextractors import FilteringLinkExtractor from scrapy.utils.response import get_base_url @@ -20,8 +18,9 @@ XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml" _collect_string_content = etree.XPath("string()") + def _nons(tag): - if isinstance(tag, basestring): + if isinstance(tag, six.string_types): if tag[0] == '{' and tag[1:len(XHTML_NAMESPACE)+1] == XHTML_NAMESPACE: return tag.split('}')[-1] return tag @@ -57,16 +56,13 @@ class LxmlParserLinkExtractor(object): url = self.process_attr(attr_val) if url is None: continue - if isinstance(url, unicode): - url = url.encode(response_encoding) + url = to_native_str(url, encoding=response_encoding) # to fix relative links after process_value url = urljoin(response_url, url) link = Link(url, _collect_string_content(el) or u'', nofollow=True if el.get('rel') == 'nofollow' else False) links.append(link) - - return unique_list(links, key=lambda link: link.url) \ - if self.unique else links + return self._deduplicate_if_needed(links) def extract_links(self, response): base_url = get_base_url(response) @@ -77,7 +73,11 @@ class LxmlParserLinkExtractor(object): The subclass should override it if neccessary """ - links = unique_list(links, key=lambda link: link.url) if self.unique else links + return self._deduplicate_if_needed(links) + + def _deduplicate_if_needed(self, links): + if self.unique: + return unique_list(links, key=lambda link: link.url) return links @@ -110,4 +110,3 @@ class LxmlLinkExtractor(FilteringLinkExtractor): links = self._extract_links(doc, response.url, response.encoding, base_url) all_links.extend(self._process_links(links)) return unique_list(all_links) - diff --git a/tests/py3-ignores.txt b/tests/py3-ignores.txt index f380e6679..b40293f57 100644 --- a/tests/py3-ignores.txt +++ b/tests/py3-ignores.txt @@ -3,7 +3,7 @@ tests/test_command_fetch.py tests/test_command_shell.py tests/test_commands.py tests/test_exporters.py -tests/test_linkextractors.py +tests/test_linkextractors_deprecated.py tests/test_crawl.py tests/test_crawler.py tests/test_downloader_handlers.py diff --git a/tests/test_link.py b/tests/test_link.py index 0b79e47cd..c8487698f 100644 --- a/tests/test_link.py +++ b/tests/test_link.py @@ -1,8 +1,10 @@ import unittest import warnings +import six from scrapy.link import Link + class LinkTest(unittest.TestCase): def _assert_same_links(self, link1, link2): @@ -43,9 +45,15 @@ class LinkTest(unittest.TestCase): l2 = eval(repr(l1)) self._assert_same_links(l1, l2) - def test_unicode_url(self): + def test_non_str_url(self): with warnings.catch_warnings(record=True) as w: - link = Link(u"http://www.example.com/\xa3") - self.assertIsInstance(link.url, bytes) - self.assertEqual(link.url, b'http://www.example.com/\xc2\xa3') - assert len(w) == 1, "warning not issued" + if six.PY2: + link = Link(u"http://www.example.com/\xa3") + self.assertIsInstance(link.url, str) + self.assertEqual(link.url, b'http://www.example.com/\xc2\xa3') + else: + link = Link(b"http://www.example.com/\xc2\xa3") + self.assertIsInstance(link.url, str) + self.assertEqual(link.url, u'http://www.example.com/\xa3') + + assert len(w) == 1, "warning not issued" diff --git a/tests/test_linkextractors.py b/tests/test_linkextractors.py index 3e202bf02..5966a3caf 100644 --- a/tests/test_linkextractors.py +++ b/tests/test_linkextractors.py @@ -3,190 +3,360 @@ import unittest import pytest -from scrapy.linkextractors.regex import RegexLinkExtractor from scrapy.http import HtmlResponse, XmlResponse from scrapy.link import Link -from scrapy.linkextractors.htmlparser import HtmlParserLinkExtractor -from scrapy.linkextractors.sgml import SgmlLinkExtractor, BaseSgmlLinkExtractor from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor from tests import get_testdata -class BaseSgmlLinkExtractorTestCase(unittest.TestCase): - def test_basic(self): - html = """
-
-
-
- """
- response = HtmlResponse("http://example.org/somepage/index.html", body=html)
+# a hack to skip base class tests in pytest
+class Base:
+ class LinkExtractorTestCase(unittest.TestCase):
+ extractor_cls = None
- lx = BaseSgmlLinkExtractor() # default: tag=a, attr=href
- self.assertEqual(lx.extract_links(response),
- [Link(url='http://example.org/somepage/item/12.html', text='Item 12'),
- Link(url='http://example.org/about.html', text='About us'),
- Link(url='http://example.org/othercat.html', text='Other category'),
- Link(url='http://example.org/', text='>>'),
- Link(url='http://example.org/', text='')])
+ def setUp(self):
+ body = get_testdata('link_extractor', 'sgml_linkextractor.html')
+ self.response = HtmlResponse(url='http://example.com/index', body=body)
- def test_base_url(self):
- html = """
"""
+ response = HtmlResponse("http://example.com/index.html", body=html)
+
+ lx = self.extractor_cls(tags=None)
+ self.assertEqual(lx.extract_links(response), [])
+
+ lx = self.extractor_cls()
+ self.assertEqual(lx.extract_links(response), [
+ Link(url='http://example.com/sample1.html', text=u''),
+ Link(url='http://example.com/sample2.html', text=u'sample 2'),
+ ])
+
+ lx = self.extractor_cls(tags="area")
+ self.assertEqual(lx.extract_links(response), [
+ Link(url='http://example.com/sample1.html', text=u''),
+ ])
+
+ lx = self.extractor_cls(tags="a")
+ self.assertEqual(lx.extract_links(response), [
+ Link(url='http://example.com/sample2.html', text=u'sample 2'),
+ ])
+
+ lx = self.extractor_cls(tags=("a","img"), attrs=("href", "src"), deny_extensions=())
+ self.assertEqual(lx.extract_links(response), [
+ Link(url='http://example.com/sample2.html', text=u'sample 2'),
+ Link(url='http://example.com/sample2.jpg', text=u''),
+ ])
+
+ def test_tags_attrs(self):
+ html = b"""
+
+
+
+
+ """
+ response = HtmlResponse("http://example.com/index.html", body=html)
+
+ lx = self.extractor_cls(tags='div', attrs='data-url')
+ self.assertEqual(lx.extract_links(response), [
+ Link(url='http://example.com/get?id=1', text=u'Item 1', fragment='', nofollow=False),
+ Link(url='http://example.com/get?id=2', text=u'Item 2', fragment='', nofollow=False)
+ ])
+
+ lx = self.extractor_cls(tags=('div',), attrs=('data-url',))
+ self.assertEqual(lx.extract_links(response), [
+ Link(url='http://example.com/get?id=1', text=u'Item 1', fragment='', nofollow=False),
+ Link(url='http://example.com/get?id=2', text=u'Item 2', fragment='', nofollow=False)
+ ])
+
+ def test_xhtml(self):
+ xhtml = b"""
+
+
+
+
+
"""
- response = HtmlResponse("http://example.com/index.html", body=html)
-
- lx = self.extractor_cls(tags=None)
- self.assertEqual(lx.extract_links(response), [])
-
- lx = self.extractor_cls()
- self.assertEqual(lx.extract_links(response), [
- Link(url='http://example.com/sample1.html', text=u''),
- Link(url='http://example.com/sample2.html', text=u'sample 2'),
- ])
-
- lx = self.extractor_cls(tags="area")
- self.assertEqual(lx.extract_links(response), [
- Link(url='http://example.com/sample1.html', text=u''),
- ])
-
- lx = self.extractor_cls(tags="a")
- self.assertEqual(lx.extract_links(response), [
- Link(url='http://example.com/sample2.html', text=u'sample 2'),
- ])
-
- lx = self.extractor_cls(tags=("a","img"), attrs=("href", "src"), deny_extensions=())
- self.assertEqual(lx.extract_links(response), [
- Link(url='http://example.com/sample2.html', text=u'sample 2'),
- Link(url='http://example.com/sample2.jpg', text=u''),
- ])
-
- def test_tags_attrs(self):
- html = """
-
-
-
-
- """
- response = HtmlResponse("http://example.com/index.html", body=html)
-
- lx = self.extractor_cls(tags='div', attrs='data-url')
- self.assertEqual(lx.extract_links(response), [
- Link(url='http://example.com/get?id=1', text=u'Item 1', fragment='', nofollow=False),
- Link(url='http://example.com/get?id=2', text=u'Item 2', fragment='', nofollow=False)
- ])
-
- lx = self.extractor_cls(tags=('div',), attrs=('data-url',))
- self.assertEqual(lx.extract_links(response), [
- Link(url='http://example.com/get?id=1', text=u'Item 1', fragment='', nofollow=False),
- Link(url='http://example.com/get?id=2', text=u'Item 2', fragment='', nofollow=False)
- ])
-
- def test_xhtml(self):
- xhtml = """
-
-
-
-
-
+
+
+
+ """
+ response = HtmlResponse("http://example.org/somepage/index.html", body=html)
+
+ lx = BaseSgmlLinkExtractor() # default: tag=a, attr=href
+ self.assertEqual(lx.extract_links(response),
+ [Link(url='http://example.org/somepage/item/12.html', text='Item 12'),
+ Link(url='http://example.org/about.html', text='About us'),
+ Link(url='http://example.org/othercat.html', text='Other category'),
+ Link(url='http://example.org/', text='>>'),
+ Link(url='http://example.org/', text='')])
+
+ def test_base_url(self):
+ html = """