【问题标题】:Debug: crawled <200>... (referer: none)调试:已抓取 <200>...(引用者:无)
【发布时间】:2020-05-21 19:25:37
【问题描述】:

我写了一个爬取非英语网站的蜘蛛,灵感来自第一个蜘蛛波纹管,但我不知道它们之间有什么区别,当我运行第一个代码时,一切似乎都很好,我得到了数据,但是运行第二个蜘蛛,我收到这条消息:Crawled (200)....(referer: none)

第一只蜘蛛:

import scrapy
import logging

class CountriesSpider(scrapy.Spider):
    name = 'countries'
    allowed_domains = ['www.worldometers.info']
    start_urls = ['https://www.worldometers.info/world-population/population-by-country/']

    def parse(self, response):
        countries = response.xpath("//td/a")
        for country in countries:
            name = country.xpath(".//text()").get()
            link = country.xpath(".//@href").get()

            yield response.follow (url= link, callback=self.parse_country, meta={'country_name':name})
    def parse_country(self, response):
        name = response.request.meta['country_name']
        rows = response.xpath("(//table[@class='table table-striped table-bordered table-hover table-condensed table-list'])[1]/tbody/tr")
        for row in rows:
            year = row.xpath(".//td[1]/text()").get()
            population = row.xpath(".//td[2]/strong/text()").get()
            yield{
                'country_name' : name,
                'year' : year,
                'population' : population
            }

第二只蜘蛛:

class xxxxxxxxSpider(scrapy.Spider):

name = 'xxxxxxx'
allowed_domains = 
['www.drsaina.com/ConsultationDoctor/%D9%85%D8%B4%D8%A7%D9%88%D8%B1%D9%87- 
 %D8%A2%D9%86%D9%84%D8%A7%DB%8C%D9%86']

start_urls =['https://www.drsaina.com/ConsultationDoctor/%D9%85%D8%B4%D8%A7%D9%88%D8%B1%D9%87 
- 
 %D8%A2%D9%86%D9%84%D8%A7%DB%8C%D9%86/']

def parse(self, response):
    specialties = response.xpath("//h3").getall()
    for specialty in specialties:
        name = specialty.xpath(".//text()").getall()
        link = specialty.xpath(".//@href").getall()
        yield response.follow(url=link, callback=self.parse_spacialty, meta = 
{'specialty_name':name})

def parse_spacialty(self, response):
    specialty_name = response.request.meta['specialty_name']
    specifications = response.xpath 
("/html/body/main/div[5]/div/div/div[2]/div[2]/ul/li[1]/div/div")
    for specification in specifications:
        doctor_name = specification.xpath(".//div[1]/a[2]/span/text()").get()
        doctor_specialty = specification.xpath 
(".//div[1]/a[2]/label/text()").get()
yield{
            'specialty_name':specialty_name,
            'doctor_name':doctor_name,
            'doctor_specialty':doctor_specialty,
}

运行第二个蜘蛛后得到的消息:

2020-05-21 10:03:47 [scrapy.utils.log] INFO: Scrapy 2.1.0 started (bot: roqaba)
2020-05-21 10:03:47 [scrapy.utils.log] INFO: Versions: lxml 4.5.0.0, libxml2 2.9
.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 20.3.0, Python 3.7.7 (d
efault, May  6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 19.1.0 (Op
enSSL 1.1.1g  21 Apr 2020), cryptography 2.9.2, Platform Windows-8.1-6.3.9600-SP
0
2020-05-21 10:03:47 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.se
lectreactor.SelectReactor
2020-05-21 10:03:47 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'roqaba',
 'NEWSPIDER_MODULE': 'roqaba.spiders',
 'ROBOTSTXT_OBEY': True,
 'SPIDER_MODULES': ['roqaba.spiders']}
2020-05-21 10:03:47 [scrapy.extensions.telnet] INFO: Telnet Password: 8eab953821
87f480
2020-05-21 10:03:47 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.logstats.LogStats']
2020-05-21 10:03:47 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2020-05-21 10:03:47 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2020-05-21 10:03:47 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2020-05-21 10:03:47 [scrapy.core.engine] INFO: Spider opened
2020-05-21 10:03:47 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pag
es/min), scraped 0 items (at 0 items/min)
2020-05-21 10:03:47 [scrapy.extensions.telnet] INFO: Telnet console listening on
 127.0.0.1:6023
2020-05-21 10:03:48 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.d
rsaina.com/robots.txt> (referer: None)
2020-05-21 10:03:49 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.d
rsaina.com/ConsultationDoctor/%D9%85%D8%B4%D8%A7%D9%88%D8%B1%D9%87-%D8%A2%D9%86%
D9%84%D8%A7%DB%8C%D9%86/> (referer: None)
2020-05-21 10:03:49 [scrapy.core.scraper] ERROR: Spider error processing <GET ht
tps://www.drsaina.com/ConsultationDoctor/%D9%85%D8%B4%D8%A7%D9%88%D8%B1%D9%87-%D
8%A2%D9%86%D9%84%D8%A7%DB%8C%D9%86/> (referer: None)
Traceback (most recent call last):
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\uti
ls\defer.py", line 117, in iter_errback
    yield next(it)
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\uti
ls\python.py", line 345, in __next__
    return next(self.data)
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\uti
ls\python.py", line 345, in __next__
    return next(self.data)
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\cor
e\spidermw.py", line 64, in _evaluate_iterable
    for r in iterable:
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\spi
dermiddlewares\offsite.py", line 29, in process_spider_output
    for x in result:
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\cor
e\spidermw.py", line 64, in _evaluate_iterable
    for r in iterable:
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\spi
dermiddlewares\referer.py", line 338, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\cor
e\spidermw.py", line 64, in _evaluate_iterable
    for r in iterable:
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\spi
dermiddlewares\urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\cor
e\spidermw.py", line 64, in _evaluate_iterable
    for r in iterable:
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\spi
dermiddlewares\depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "c:\users\pc\anaconda3\envs\vitual_workspace\lib\site-packages\scrapy\cor
e\spidermw.py", line 64, in _evaluate_iterable
    for r in iterable:
  File "C:\Users\pc\projects\roqaba\roqaba\spiders\darmankade.py", line 19, in p
arse
    name = specialty.xpath(".//text()").getall()
AttributeError: 'str' object has no attribute 'xpath'
2020-05-21 10:03:49 [scrapy.core.engine] INFO: Closing spider (finished)
2020-05-21 10:03:49 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 533,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 44908,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'elapsed_time_seconds': 1.56041,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 5, 21, 5, 33, 49, 446308),
 'log_count/DEBUG': 2,
 'log_count/ERROR': 1,
 'log_count/INFO': 10,
 'response_received_count': 2,
 'robotstxt/request_count': 1,
 'robotstxt/response_count': 1,
 'robotstxt/response_status_count/200': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'spider_exceptions/AttributeError': 1,
 'start_time': datetime.datetime(2020, 5, 21, 5, 33, 47, 885898)}
2020-05-21 10:03:49 [scrapy.core.engine] INFO: Spider closed (finished)

顺便说一句,如果重要的话,我正在使用 scrapy 2.1 和 python 3。

有人可以帮我解决第二个代码吗?

谢谢

【问题讨论】:

    标签: python debugging web-scraping scrapy


    【解决方案1】:

    您的蜘蛛程序中至少存在三个问题。我注意到的第一个是您的 allowed_domains 字段。您应该使其不那么具体,否则您可能无法请求另一个网址。我认为这应该足够了:

    allowed_domains = ['www.drsaina.com']
    

    下一个问题是您的 parse 方法。您正在使用getall() 提取所有h3,它返回一个字符串列表,然后您尝试使用xpath() 从这些字符串中提取。下一个问题是您调用getall() 来提取名称和链接。我认为您要调用的是get()extract_first(),它们都返回一个字符串。
    将其更改为以下内容,您的错误消息应该会更改。

    def parse(self, response):
        specialties = response.xpath("//h3")
        for specialty in specialties:
            name = specialty.xpath(".//text()").extract_first()
            link = specialty.xpath(".//@href").extract_first()
            yield response.follow(url=link, callback=self.parse_spacialty, meta={'specialty_name': name})
    

    【讨论】:

    • 你好@Patrick K。谢谢你的建议。当我按照您所说的进行操作时,错误从“AttributeError:'str' object has no attribute 'xpath'”变为“ValueError: URL can't be None”。在这两种情况下,与“Crawled (200) (referer: None)”相关的错误保持不变。我不知道这些错误是关于什么的。当我得到 .csv 导出文件时,文件已创建但它是空的。
    • @shimamasaeli 完美!这意味着链接的 xpath 可能是错误的。我可以看到您正在尝试从 h3 元素中提取 href 。这些通常没有href。您可能应该在包含您需要关注的链接的页面上搜索 a 标签。
    • 呜呜呜!!我永远无法想象这可能是一千年后的原因!非常感谢,哈哈:)))
    • @shimamasaeli 很高兴能帮上忙 :)
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 2015-11-18
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    相关资源
    最近更新 更多