Python 模式中 re.search 的类型错误

Python TypeError for re.search in patterns

您可以在此处查看完整文件:https://github.com/slideri812/pyhotn/blob/main/tapt.py 我大约 6 个月前写了这篇文章,并且效果很好。我每周一次 运行 与其他 2 个人一起编写此脚本。前几天,在 950 多页之后,它遇到了一个错误:TypeError: expected string or bytes-like object.

在过去的 5 天里,我尝试了各种方法来解决这个问题,但没有任何效果。我已经审查了很多文章,但看起来我所做的一切都很好。我认为它可能特定于该一页,但找不到问题或让它越过错误页面。我卡住了。

这是完整的错误:


TypeError                                 Traceback (most recent call last)
 in 
    159 
    160         for pattern in patterns:
--> 161             if re.search(pattern, text_to_search):
    162                 break
    163             else:

c:\users\slide\appdata\local\programs\python\python38-32\lib\re.py in search(pattern, string, flags)
    197     """Scan through string looking for a match to the pattern, returning
    198     a Match object, or None if no match was found."""
--> 199     return _compile(pattern, flags).search(string)
    200 
    201 def sub(pattern, repl, string, count=0, flags=0):

TypeError: expected string or bytes-like object

网站一直在添加和删除列表,这不是问题。我已经检查了它抛出错误的页面,它之前的页面,一切看起来都很好,但显然不是。 我有内置的错误处理功能,因为我预计有时会出现没有数据的情况。

此位从字段中获取数据:


    #location
    try:
        data_dict["location"] = detail.find("a",{"id":"myDataList_lblLocation_1"}).text.strip()[10:]
    except AttributeError as e:
        data_dict["location"] = None

    try:
        data_dict["location2"] = detail.find("span",{"id":"lblAddress"}).text.strip()
    except AttributeError as e:
        data_dict["location2"] = None

这是我的逻辑。我在字符串中搜索城市名称并匹配该名称以应用特定编码:


    #major
    patterns = ["Bangkok", "Phuket", "Chiang Mai", "Pattaya", "Chon Buri", "None"]
    text_to_search = (data_dict["location"])
    
    for pattern in patterns:
        if re.search(pattern, text_to_search):
            break
    
    if pattern == "Bangkok":
        data_dict["major locations"] = "54fbfc7f-a0cf-4a1d-9361-6059a44c2415"
    elif pattern == "Phuket":
        data_dict["major locations"] = "cbad67b4-7870-4ee2-b8a3-62d8c9f87091"
    elif pattern == "Chiang Mai":
        data_dict["major locations"] = "2966d83a-04f9-4b4e-b27e-05afe700b13f"
    elif pattern == "Pattaya":
        data_dict["major locations"] = "fbfaabca-0e9e-4db4-be1c-6cc8e8b8f63d"
    elif pattern == "Chon Buri":
        data_dict["major locations"] = "ce1da47b-78b6-4351-b849-e337db181c6a"
    elif pattern == "None":
        data_dict["major locations"] = "None"            
    else:
        data_dict["major locations"] = "No Match Found"

如果能提供一些帮助,我们将不胜感激。我通常能够自己解决这些问题,通常是通过阅读和/或尝试不同的方法,但这次不行。

提前致谢

乍一看,在第 120 行,你有这个块:

try:
    data_dict["location"] = detail.find("a",{"id":"myDataList_lblLocation_1"}).text.strip()[10:]
except AttributeError as e:
    data_dict["location"] = None

我的猜测是您遇到了属性错误并将 None 存储为值。然后当你稍后去正则表达式搜索它时,你会遇到 TypeError。在 except 块中放入打印或日志语句以确认