scrapy 获取下一行匹配的正则表达式返回空

chhqkbe1  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(108)

根据这个正则表达式code来获取匹配的下一行,我的代码的注解行在我添加了“+([^\r\n]+)“之后应该可以工作了。但是由于某些原因它不工作了...我是正则表达式的新手,所以任何提示都是非常受欢迎的。

import scrapy
import json
class MlSpider(scrapy.Spider):
url1='https://produto.mercadolivre.com.br/MLB-1304118411-sandalia-feminina-anabela-confortavel-pingente-mac-cod-133-_JM?attributes=COLOR_SECONDARY_COLOR%3AUHJldGE%3D%2CSIZE%3AMzU%3D&quantity=1'
url2='https://www.mercadolivre.com.br/chinelo-kenner-rakka-pretolaranja-36-br-para-adulto-homem/p/MLB19132834?product_trigger_id=MLB19130858&attributes=COLOR%3APreto%2FAzul%2CSIZE%3A36+BR&pdp_filters=category%3AMLB273770%7Cshipping_cost%3Afree&applied_product_filters=MLB19132871&quantity=1'   
   name = 'detalhador'
   start_urls=[url2] 

   def parse(self, response,**kwargs):
           d = response.xpath("//script[contains(., 'window.__PRELOADED_STATE__')]/text()").re_first(r'(?s)window.__PRELOADED_STATE__ = (.+?\});') # This only gets url1, because the following text of the string is in the same line as the string

           if not d : # so this was made to get url2 as well
                d = response.xpath("//script[contains(., 'window.__PRELOADED_STATE__')]/text()").re_first(r'(?s)window.__PRELOADED_STATE__ = +([^\r\n]+)') #This should get the line bellow the matching string, but i dosent
von4xj4u

von4xj4u1#

问题出在您的正则表达式上。您没有转义正则表达式内部用作解析工具和方向的某些符号。您还使用了文字' '空格字符,而实际上在=符号后面紧接着一个换行符。使用\s通常更好,因为它表示任何空格字符。
试着用这个代替。我已经测试过了,得到了你想要的结果。

d = response.xpath("//script[contains(., 'window.__PRELOADED_STATE__')]/text()"
                   ).re_first(r'window\.__PRELOADED_STATE__\s?\=\s*?(\{.*?\});')

.{}=字符都被正则表达式用作解析指令,因此当您希望在表达式中使用文字字符时,需要使用\对它们进行转义。
我还删除了表达式开头的(?s),我不完全确定为什么会有这个。

相关问题