Scrapy LinkExtractor匹配含sortiment/的URL失败问题求助
关于Scrapy爬取willys.se网站sortiment链接的问题
我正尝试使用Scrapy爬取名为willys的网站(https://www.willys.se/),想要获取该网站所有URL中包含"sortiment/"的链接。但设置allow=r"sortiment/"(目标链接示例:https://www.willys.se/sortiment/)后,爬虫仅爬取主页就停止运行。在其他网站使用相同逻辑可以正常运行,如果去掉allow参数(allow=None),爬虫能获取页面上的所有链接,怀疑是该网站的URL存在匹配问题,希望得到解决建议。
爬虫代码
from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from bs4 import BeautifulSoup class Spider(CrawlSpider): name = 'spider' start_urls = ["https://www.willys.se/"] allowed_domains = ["www.willys.se"] rules = ( Rule(LinkExtractor(allow=r"sortiment/"), callback="parse", follow=True), ) def parse(self, response): print("Parsing URL:", response.url) with open('response_content.txt', 'w', encoding="utf-8") as f: soup = BeautifulSoup(response.text,"html.parser") f.write(soup.prettify())
启动命令
scrapy crawl spider
运行输出
2023-08-02 16:21:28 [scrapy.utils.log] INFO: Scrapy 2.9.0 started (bot: my_project_name) 2023-08-02 16:21:28 [scrapy.utils.log] INFO: Versions: lxml 4.9.3.0, libxml2 2.10.3, cssselect 1.2.0, parsel 1.8.1, w3lib 2.1.1, Twisted 22.10.0, Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)], pyOpenSSL 23.2.0 (OpenSSL 3.1.1 30 May 2023), cryptography 41.0.2, Platform Windows-10-10.0.22621-SP0 2023-08-02 16:21:28 [scrapy.crawler] INFO: Overridden settings: {'AUTOTHROTTLE_ENABLED': True, 'AUTOTHROTTLE_TARGET_CONCURRENCY': 0.5, 'BOT_NAME': 'my_project_name', 'COOKIES_ENABLED': False, 'DOWNLOAD_DELAY': 3, 'FEED_EXPORT_ENCODING': 'utf-8', 'NEWSPIDER_MODULE': 'my_project_name.spiders', 'REQUEST_FINGERPRINTER_IMPLEMENTATION': '2.7', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['my_project_name.spiders'], 'TWISTED_REACTOR': 'twisted.internet.asyncioreactor.AsyncioSelectorReactor'} 2023-08-02 16:21:28 [asyncio] DEBUG: Using selector: SelectSelector 2023-08-02 16:21:28 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor 2023-08-02 16:21:28 [scrapy.utils.log] DEBUG: Using asyncio event loop: asyncio.windows_events._WindowsSelectorEventLoop 2023-08-02 16:21:28 [scrapy.extensions.telnet] INFO: Telnet Password: 5130cc64f37e65de 2023-08-02 16:21:28 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats', 'scrapy.extensions.throttle.AutoThrottle'] 2023-08-02 16:21:28 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware', 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2023-08-02 16:21:28 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2023-08-02 16:21:28 [scrapy.middleware] INFO: Enabled item pipelines: [] 2023-08-02 16:21:28 [scrapy.core.engine] INFO: Spider opened 2023-08-02 16:21:29 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2023-08-02 16:21:29 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023 2023-08-02 16:21:29 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.willys.se/robots.txt> (referer: None) 2023-08-02 16:21:34 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.willys.se/> (referer: None) 2023-08-02 16:21:34 [scrapy.core.engine] INFO: Closing spider (finished) 2023-08-02 16:21:34 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 436, 'downloader/request_count': 2, 'downloader/request_method_count/GET': 2, 'downloader/response_bytes': 106051, 'downloader/response_count': 2, 'downloader/response_status_count/200': 2, 'elapsed_time_seconds': 5.879534, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2023, 8, 2, 14, 21, 34, 884435), 'httpcompression/response_bytes': 405009, 'httpcompression/response_count': 2, 'log_count/DEBUG': 5, 'log_count/INFO': 10, 'response_received_count': 2, 'robotstxt/request_count': 1, 'robotstxt/response_count': 1, 'robotstxt/response_status_count/200': 1, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'start_time': datetime.datetime(2023, 8, 2, 14, 21, 29, 4901)} 2023-08-02 16:21:34 [scrapy.core.engine] INFO: Spider closed (finished)
解决建议
- 检查Robots协议限制:从日志看爬虫开启了
ROBOTSTXT_OBEY: True,先查看网站的robots.txt内容,确认是否禁止爬取sortiment相关路径。如果有封禁规则,可将ROBOTSTXT_OBEY设为False(注意遵守网站爬虫协议,避免违规)。 - 调整正则匹配规则:当前
allow=r"sortiment/"仅匹配带斜杠的路径,实际页面中的链接可能是无斜杠的sortiment或带参数的形式。可放宽规则为allow=r"sortiment",或者更精准匹配路径前缀allow=r"/sortiment"。 - 查看页面实际链接格式:打开保存的
response_content.txt,搜索页面中的sortiment相关链接,确认是否为相对路径、是否有URL编码,或是通过JavaScript动态加载的。如果是动态加载的链接,需要使用scrapy-splash或直接解析页面内的JS数据来提取。 - 添加User-Agent模拟真实浏览器:部分网站会拦截Scrapy默认请求头,在项目的
settings.py中添加浏览器UA:USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
内容的提问来源于stack exchange,提问作者Calle1289
相关产品推荐
相关产品推荐

