【发布时间】:2015-11-06 19:38:44
【问题描述】:
我知道 html 中有一个命令:var x = document.domain; 可以获取域,但是我如何在 Scrapy 中实现它以便获取域名?
【问题讨论】:
我知道 html 中有一个命令:var x = document.domain; 可以获取域,但是我如何在 Scrapy 中实现它以便获取域名?
【问题讨论】:
你可以从response.urlextract the domain name:
from urlparse import urlparse
def parse(self, response):
parsed_uri = urlparse(response.url)
domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print domain
【讨论】:
对于 Python3,'from' 和 'print' 的两个非常小的变化。 alecxe 的回答对 Python2 有好处。
另外,对于 Scrapy 的 CrawlSpider,将上面的名称 'parse' 更改为其他名称,因为 CrawlSpider 自己使用 'parse'。
from urllib.parse import urlparse
def get_domain(self, response):
parsed_uri = urlparse(response.url)
domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print(domain)
return domain
那你就可以用它了,作为OP的例子
x = get_domain
或者就我而言,我想将域传递给 Scrapy 的 CrawlSpider 的 Rule 的 LinkExtractor 的 allow_domains。呸。这会将爬网限制到该域。
rules = [
Rule(
LinkExtractor(
canonicalize=True,
unique=True,
strip=True,
allow_domains=(domain)
),
follow=True,
callback="someparser"
)
]
【讨论】:
试试:
_rl = response.url
url = _rl.split("/")[2]
print (url)
【讨论】: