我正在使用Scrapy制作电子邮件刮板,但不断出现此错误: TypeError:无法在类似字节的对象上使用字符串模式
这是我正在使用的Python代码:
import re
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class EmailSpider(CrawlSpider):
name = 'EmailScraper'
emailHistory = {}
custom_settings = {
'ROBOTSTXT_OBEY': False
# ,'DEPTH_LIMIT' : 6
}
emailRegex = re.compile((r"([a-zA-Z0-9_{|}~-]+(?:\.[a-zA-Z0-9_"
r"{|}~-]+)*(@)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9]){2,}?(\."
r"))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))
def __init__(self, url=None, *args, **kwargs):
super(EmailSpider, self).__init__(*args, **kwargs)
self.start_urls = [url]
self.allowed_domains = [url.replace(
"http://", "").replace("www.", "").replace("/", "")]
rules = (Rule(LinkExtractor(), callback="parse_item", follow=True),)
def parse_item(self, response):
emails = re.findall(EmailSpider.emailRegex, response._body)
for email in emails:
if email[0] in EmailSpider.emailHistory:
continue
else:
EmailSpider.emailHistory[email[0]] = True
yield {
'site': response.url,
'email': email[0]
}
我看到了很多答案,但是我对python还是很陌生,所以我不确定如何实现代码中给出的代码。
因此,如果您不介意的话,还可以告诉我将代码放入其中。
感谢裘德·威尔逊
答案 0 :(得分:0)
response._body
不是str
(字符串对象),因此不能在其上使用re
(regex)。如果您查找其对象类型,则会发现它是bytes
(字节对象)。
>>> type(response._body)
<class 'bytes'>
通过将其解码为类似UTF-8的格式,应该可以解决该问题。
>>> type(response._body.decode('utf-8'))
<class 'str'>
最终re
像这样:
emails = re.findall(EmailSpider.emailRegex, response._body.decode('utf-8'))