Skip to main content
 首页 » 编程设计

python之Scrapy的这个正则表达式怎么写

2025年05月04日27java哥

HTML:

<html> 
 <head> 
  <base href='http://example.com/' /> 
  <title>Example website</title> 
 </head> 
 <body> 
  <div id='demo'> 
 <div>Fruite:Apple&nbsp;&nbsp;&nbsp;&nbsp;Sport:Football&nbsp;&nbsp;&nbsp;&nbsp;Language:English</div> 
  </div> 
 </body> 
</html> 

我想得到这3个结果,如下:

>>> response.xpath('//div[@id="demo"]/div/text()').re(r'') 
u'Apple' 
 
>>> response.xpath('//div[@id="demo"]/div/text()').re(r'') 
u'Football' 
 
>>> response.xpath('//div[@id="demo"]/div/text()').re(r'') 
u'English' 

上面re()中的正则表达式怎么写?

请您参考如下方法:

\w+ 应该这样做。其中\w为单词字符,+为贪心量词。

In: response.xpath('//div[@id="demo"]/div/text()').re(r'\w+')   
Out: ['Fruite', 'Apple', 'Sport', 'Football', 'Language', 'English']   

您可以预先附加 : 以仅获取冒号后的单词::(\w+)

In: response.xpath('//div[@id="demo"]/div/text()').re(r':(\w+)') 
Out: ['Apple', 'Football', 'English'] 

如果您只需要特定的词,那么您可以使用 |(或分隔符)简单地列出您的词:

In: response.xpath('//div[@id="demo"]/div/text()').re(r'Apple|Football|English') 
Out: ['Apple', 'Football', 'English']