【问题标题】:How to fix this type error thrown by regular expression in python?如何修复python中正则表达式引发的这种类型错误?
【发布时间】:2019-08-08 17:13:29
【问题描述】:

我正在尝试收集 Python Requests 库的所有内部链接并过滤掉所有外部链接。

我正在使用正则表达式来做同样的事情。但是它抛出了我无法解决的这种类型的错误。

我的代码:

import requests
from bs4 import BeautifulSoup
import re

r = requests.get('https://2.python-requests.org/en/master/')
content = BeautifulSoup(r.text)
[i['href'] for i in content.find_all('a') if not re.match("http", i)]

错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-10-b7d82067fe9c> in <module>
----> 1 [i['href'] for i in content.find_all('a') if not re.match("http", i)]

<ipython-input-10-b7d82067fe9c> in <listcomp>(.0)
----> 1 [i['href'] for i in content.find_all('a') if not re.match("http", i)]

~\Anaconda3\lib\re.py in match(pattern, string, flags)
    171     """Try to apply the pattern at the start of the string, returning
    172     a Match object, or None if no match was found."""
--> 173     return _compile(pattern, flags).match(string)
    174 
    175 def fullmatch(pattern, string, flags=0):

TypeError: expected string or bytes-like object

【问题讨论】:

    标签: python regex python-3.x list-comprehension


    【解决方案1】:

    您传递给它的是一个 BeautifulSoup 节点对象,而不是一个字符串。试试这个:

    [i['href'] for i in content.find_all('a') if not re.match("http", i['href'])]
    

    【讨论】:

    • re.match("http", i['href']) 最好写成i['href'].startswith("http")
    • 两种解决方案都有效!感谢您解释我哪里出错了@Robert
    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 2021-08-03
    • 2020-05-03
    • 2016-04-15
    • 1970-01-01
    • 2021-11-14
    • 2017-04-05
    • 2021-02-17
    相关资源
    最近更新 更多