San*_*pta 12 python url web-crawler scrapy
我正在使用scrapy来抓取一个网站,该网站似乎将随机值附加到每个网址末尾的查询字符串中.这使得爬行成为一种无限循环.
如何让scrapy忽略URL的查询字符串部分?
Sja*_*aak 24
示例代码:
from urlparse import urlparse
o = urlparse('http://url.something.com/bla.html?querystring=stuff')
url_without_query_string = o.scheme + "://" + o.netloc + o.path
Run Code Online (Sandbox Code Playgroud)
示例输出:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from urlparse import urlparse
>>> o = urlparse('http://url.something.com/bla.html?querystring=stuff')
>>> url_without_query_string = o.scheme + "://" + o.netloc + o.path
>>> print url_without_query_string
http://url.something.com/bla.html
>>>
Run Code Online (Sandbox Code Playgroud)
提供一些代码,以便我们为您提供帮助.
如果你正在使用CrawlSpider和Rule的带SgmlLinkExtractor,提供定制功能proccess_value的参数SgmlLinkExtractor的构造函数.
def delete_random_garbage_from_url(url):
cleaned_url = ... # process url somehow
return cleaned_url
Rule(
SgmlLinkExtractor(
# ... your allow, deny parameters, etc
process_value=delete_random_garbage_from_url,
)
)
Run Code Online (Sandbox Code Playgroud)
您可以使用该urllib.parse.urlsplit()功能。结果是一个结构化的解析结果,一个具有附加功能的命名元组。
使用该namedtuple._replace()方法更改解析结果值,然后使用该SplitResult.geturl()方法再次获取 URL 字符串。
要删除查询字符串,请将query值设置为None:
from urllib.parse import urlsplit
updated_url = urlsplit(url)._replace(query=None).geturl()
Run Code Online (Sandbox Code Playgroud)
演示:
>>> from urllib.parse import urlsplit
>>> url = 'https://example.com/example/path?query_string=everything+after+the+questionmark'
>>> urlparse.urlsplit(url)._replace(query=None).geturl()
'https://example.com/example/path'
Run Code Online (Sandbox Code Playgroud)
对于 Python 2,相同的函数在urlparse.urlsplit()名称下可用。
您也可以使用该urllparse.parse.urlparse()功能;对于没有任何路径参数的URL ,结果将是相同的。这两个函数在处理路径参数的方式上有所不同;urlparse()仅支持路径最后一段的urlsplit()路径参数,而将路径参数留在路径中,将此类参数的解析留给其他代码。由于这些天很少使用路径参数(后来的 URL RFC 完全放弃了该功能),因此差异是学术上的。urlparse()使用urlsplit()和不带参数,除了额外的开销外不会增加任何东西。最好urlsplit()直接使用。