Skip to main content
 首页 » 编程设计

python之TypeError : cannot concatenate 'str' and 'NoneType' objects when placing the custom url in scrapy. 请求()

2024年10月17日7myhome

我得到一个无法用于从下一页获取数据的 url,因此创建了一个 base_url = 'http://www.marinetraffic.com' 变量并向其传递了 scrapy 请求。 port_homepage_url = base_url + port_homepage_url。当我得到这样的结果时,它工作正常。 yield {'a': port_homepage_url, 'b':item['port_name']} 我得到了我想要的结果。

http://www.marinetraffic.com/en/ais/index/ships/range/port_id:20585/port_name:FUJAIRAH%20ANCH,FUJAIRAH anchor

但是,如果将它放在 scrapy 请求中 yield scrapy.Request(port_homepage_url, callback=self.parse, meta={'item': item}) 我得到错误

port_homepage_url = base_url +  port_homepage_url 
TypeError: cannot concatenate 'str' and 'NoneType' objects 

这是代码

class GetVessel(scrapy.Spider): 
    name = "getvessel" 
    allowed_domains = ["marinetraffic.com"] 
    start_urls = [ 
        'http://www.marinetraffic.com/en/ais/index/ports/all/flag:AE', 
    ] 
 
 
    def parse(self, response): 
        item = VesseltrackerItem() 
        base_url = 'http://www.marinetraffic.com' 
        for ports in response.xpath('//table/tr[position()>1]'): 
            item['port_name'] = ports.xpath('td[2]/a/text()').extract_first() 
            port_homepage_url = ports.xpath('td[7]/a/@href').extract_first() 
            port_homepage_url = base_url +  port_homepage_url 
            yield scrapy.Request(port_homepage_url, callback=self.parse, meta={'item': item}) 

请您参考如下方法:

该问题不会发生在最初的起始 URL 页面上,但会在稍后处理后续请求时发生。以this page为例.第 7 个 td 元素中没有链接,因此 ports.xpath('td[7]/a/@href').extract_first() 返回None 导致 port_homepage_url = base_url + port_homepage_url 行失败。

如何解决问题取决于您打算在“端口”页面上做什么。据我了解,您并不是要使用 self.parse 实际处理“端口”页面请求,而是需要一个单独的回调函数,其中包含不同的逻辑。