【问题标题】:TypeError: 'NoneType' object is not iterable even though it says it's a string, why is that so?TypeError: 'NoneType' object is not iterable 即使它说它是一个字符串,为什么会这样?
【发布时间】:2020-05-03 16:41:03
【问题描述】:

此功能的目标是检查亚马逊商品是否不可用。

def check(url):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
        page = requests.get(url, headers = headers)

        doc = html.fromstring(page.content)
        XPATH_AVAILABILITY = '//div[@id ="availability"]//text()'
        RAw_AVAILABILITY = doc.xpath(XPATH_AVAILABILITY)
        AVAILABILITY = ''.join(RAw_AVAILABILITY).strip()
        if any(re.match(r'unavailable', str(AVAILABILITY), re.IGNORECASE)):
            return "UNAVAILABLE"
        else:
            return "AVAILABLE"

我检查了AVAILABILITY变量(它是字符串)的type(),当项目不可用时它看起来像这样:

Currently unavailable.
        
        
    
    
    
    



    
    
         
        
        
            We don't know when or if this item will be back in stock.

当它可用时像这样(类型:字符串):

In Stock.In stock.

这就是为什么我选择正则表达式来检测输出中的“不可用”。但是错误说:

文件“scra.py”,第 68 行,在

如果有(re.match(r'unavailable', check(i), re.IGNORECASE)):

TypeError: 'NoneType' 对象不可迭代

它从不输出“无”,这就是我感到惊讶的原因。请帮我解决这个问题。

【问题讨论】:

  • 我尝试了re.findall,但出现错误。我尝试了搜索,同样的事情发生了。
  • @Carcigenicate 我尝试搜索而不是匹配,发生错误:TypeError: '_sre.SRE_Match' object is not iterable

标签: python regex web-scraping


【解决方案1】:

any(x) 迭代 x 并在找到评估为 true 的元素时返回 True,如果到达末尾则返回 False

re.match 如果找到匹配项,则返回 Match 对象或 None

您的内容不能与正则表达式匹配,re.match 返回None 并且any 不能对其进行迭代。

【讨论】:

  • 即使是这样,匹配对象也不是可迭代的,我很确定
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-17
相关资源
最近更新 更多