使用scrapy在正文中查找电子邮件地址

use*_*245 6 python xpath scrapy

我正在尝试使用scrapy查找页面上的所有电子邮件地址。

我找到了一个应该返回电子邮件地址的 xpath,但是当我运行下面的代码时,它没有找到任何电子邮件地址(我知道在那里)。我收到如下错误:

文件“C:\Anaconda2\lib\site-packages\scrapy\selector\unified.py”,第 100 行,在 xpath 中引发 ValueError(msg if Six.PY3 else msg.encode("unicode_escape")) ValueError: Invalid XPath: //[-a-zA-Z0-9. ]+@[-a-zA-Z0-9 ]+.[a-zA-Z0-9_.]+

这就是我的代码的样子。有人能告诉我我做错了什么吗?

我已将问题缩小到 xpath,但无法弄清楚如何解决它。

import scrapy
import datetime
from scrapy.spiders import CrawlSpider
from techfinder.items import EmailItem
from scrapy.selector import HtmlXPathSelector


class DetectSpider(scrapy.Spider):
    name = "test"

    alloweddomainfile = open("emaildomains.txt")
    allowed_domains = [domain.strip() for domain in alloweddomainfile.readlines()]
    alloweddomainfile.close()

    starturlfile = open("emailurls.txt")
    start_urls = [url.strip() for url in starturlfile.readlines()]
    starturlfile.close()


    def parse(self, response):




        hxs = HtmlXPathSelector(response)


        emails = hxs.xpath('//[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+').extract()             
        #[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+
        #<a\s+href=\"mailto:([a-zA-Z0-9._@]*)\
        #/^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i



        emailitems = []
        for email in zip(emails):
            emailitem = EmailItem()
            emailitem["email"] = emails
            emailitem["source"] = response.url
            emailitem["datetime"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            emailitems.append(emailitem)
        return emailitems
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以在response.body 上使用正则表达式搜索来查找电子邮件ID。

emails = re.findall(r'[\w\.-]+@[\w\.-]+', response.body)
Run Code Online (Sandbox Code Playgroud)