【问题标题】:Unable to use "regex" within scrapy无法在scrapy中使用“正则表达式”
【发布时间】:2018-09-20 15:52:33
【问题描述】:

如何在scrapy 中使用regex?我搜索了很多,但找不到任何好的指导。但是,我尝试过如下操作,但它引发了一个异常,我将在下面粘贴。

import requests, re
from scrapy import Selector

LINK = 'http://www.viperinnovations.com/products-and-services/cableguardian'

def get_item(url):
    res = requests.get(url)
    sel = Selector(res)
    email = re.findall(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+',sel)[0]
    print(email)

if __name__ == '__main__':
    get_item(LINK)

执行时抛出的异常:

Traceback (most recent call last):
  File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\demo.py", line 13, in <module>
    get_item(LINK)
  File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\demo.py", line 9, in get_item
    email = re.findall(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+',sel)[0]
  File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\lib\re.py", line 222, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

上面我的爬虫中的电子邮件只是一个占位符。我只想知道如何在scrapy 中使用regex。感谢您的帮助。

【问题讨论】:

  • A Selector 不是字符串,您可以使用它从原始数据中选择子字符串。所以我不确定你想让re.findall(…, sel) 做什么。如果你想选择整个输入,你可以通过sel.extract() 来做,但那是没有意义的;传递整个字符串比选择整个字符串并传递结果更容易。如果你想让它做一些不同的事情,你需要解释你真正想做的事情。

标签: python regex python-3.x web-scraping scrapy


【解决方案1】:

Selector 不是字符串,它是一个知道如何对 HTML 字符串或响应对象运行查询以查找子元素的对象。

一旦你找到了你想要的一个或多个元素(如果有任何非奇异查询,它会找到一个元素列表),extract 方法会让你得到找到的一个或多个元素的文本。

例如:

>>> Selector(text=body)
<Selector (text)>
>>> Selector(text=body).xpath('//span/text()')
<Selector (text) xpath=//title/text()>
>>> Selector(text=body).xpath('//span/text()').extract()
['First span', 'Second span', 'Third span']

这只是你可以用正则表达式做任何有用的最后一个:

>>> [match
...  for text in Selector(text=body).xpath('//span/text()').extract()
...  for match in re.findall(r'[a-z]*\s', text)]
['irst ', 'econd ', 'hird ']

【讨论】:

  • 感谢@abarnert,提供如此出色的解决方案。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 2015-03-20
  • 2016-09-26
  • 2015-12-18
  • 2020-09-14
  • 2017-01-18
相关资源
最近更新 更多