【问题标题】:why my crawlspider doesn't work well?为什么我的爬虫不能正常工作?
【发布时间】:2014-12-05 06:13:34
【问题描述】:

我想从网站获取一些数据,所以我用scrapy写了一个蜘蛛,但是当我回调另一个“parse_zai”时,它似乎失败了,我该如何完成呢?请帮助!!

代码在这里

# encoding utf-8

from scrapy.http import Request

from scrapy.selector import Selector

from scrapy.contrib.spiders import CrawlSpider,Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from tencentnews.items import TencentnewsItem
class Tencentnews_spider(CrawlSpider):
    name = "Tnews"
    allowed_domains = ["news.qq.com"]#It's the web i scrapyed
    start_urls = [
         "http://news.qq.com/china_index.shtml",
         "http://news.qq.com/world_index.shtml",
         "http://news.qq.com/society_index.shtml", 
             ]
    rules = [
        Rule(SgmlLinkExtractor(allow=('/a/\d{8}/\d{6}\.htm',)),follow=True,callback='parse_item'),
        Rule(SgmlLinkExtractor(allow=('/(.+)\.shtml', )), follow=True),
            ]

主要

    def parse_item(self, response):
        self.log('Hi, this is an item page! %s' % response.url)
        sel = Selector(response)
        item = TencentnewsItem()


        item['articlename'] = sel.xpath("//div[@id='C-Main-Article-QQ']/div[1]/h1/text()").extract() #get the news'article  
        item['reportsource'] = sel.xpath("//span[@class='color-a-1']/a/text()").extract()
        item['articletime'] = sel.xpath("//span[@class='article-time']/text()").extract()
        item['commentnumber'] = sel.xpath("//a[@id='cmtNum']/text()").extract()
        item['commenturl'] = sel.xpath("//a[@id='cmtNum']/@href").extract()
        print repr(item).decode("unicode-escape") + '\n'
        for url in item['commenturl']:
            request = Request(url,callback = self.parse_zai)
            request.meta['item'] = item 
        return request

    def parse_zai(self,response):
        print 'helloworld'
        sel = Selector(response)
        item = response.meta['item']

        item['title'] = sel.xpath("//div[@class='bigTitle']/h1/a/text()").extract()

        print repr(item).decode("unicode-escape") + '\n'    
        return item

【问题讨论】:

  • “似乎失败了”是什么意思?您收到的错误消息是什么?
  • 查看网站后,我发现commenturlcoral.qq.com/xxx 现在在allowed_domains 中。将域添加到 allowed_domains,或仅删除 allow_domains 属性。
  • 因为 parse_zai 不返回任何结果,即使是“helloworld”,太伤心了!

标签: python scrapy


【解决方案1】:

我可以看到你没有使用标题

用户代理是浏览器用来向 Web 服务器标识自己的字符串。它在请求头中的每个 HTTP 请求上发送,在 Scrapy 的情况下,它标识如下;


   def header(self):
         headers =  {         
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36',
                'Accept': 'application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding': 'gzip, deflate, sdch',
                'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
        }
        return headers 


Request(url,callback = self.parse_zai, headers = headers)


在文件中使用 Python 打印日志 如果你想在文件中而不是在控制台上打印 python 日志,那么我们可以使用 basicConfig() 方法通过提供文件名和文件模式作为参数来实现。

消息的格式可以通过basicConfig()方法中的format参数指定。

import logging    # first of all import the module

logging.basicConfig(filename='std.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This message will get logged on to a file')


  1. 首先,只需导入日志模块。
  2. 第二步是创建和配置记录器。
  3. 第三步,也可以设置记录器的格式。
  4. 您还可以设置记录器的级别。


logger.debug("This is debug message") 
logger.info("This is information message") 
logger.warning("This is Warning message") 
logger.error("This is error message")

通过使用它,您还可以将输出存储到日志文件中

您可以使用此链接获取更多深度信息 我给出了一些网站的一些链接,他们给出了用户代理的详细信息

https://www.scrapehero.com/how-to-fake-and-rotate-user-agents-using-python-3/

【讨论】:

    【解决方案2】:

    查看网站后发现commenturl域coral.qq.com/xxx不在 allowed_domains。

    将域添加到 allowed_domains,或仅删除 allow_domains 属性。

    您可以通过过滤您的scrapy loglevel DEBUG日志来检查您的请求是否由于allowed_domains而失败。

    grep "DEBUG: Filtered offsite request" yourlogfile.log
    

    顺便说一句,日志将只打印不在 allowed_domains 中的第一个域,以保持日志干净。

    DEBUG: Filtered offsite request to 'www.example.com': <GET http://www.example.com>
    

    文档:OffsiteMiddleware

    【讨论】:

    • 谢谢,我试试
    • 感谢您的帮助,我已经按照您说的解决了问题,(“删除 allowed_domain 属性”)
    猜你喜欢
    • 2017-11-07
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多