【问题标题】:TypeError: 'in <string>' requires string as left operand, not re.Pattern [duplicate]TypeError:'in <string>' 需要字符串作为左操作数,而不是 re.Pattern [重复]
【发布时间】:2021-07-29 04:59:49
【问题描述】:

运行以下代码时

sneaker_info.find(lambda tag: tag.name == 'td' and re.compile('Size') in tag.text)

我收到此错误

TypeError: 'in <string>' requires string as left operand, not re.Pattern

我知道我可以使用 sneaker_info.find(lambda tag: tag.name == 'td' and 'Size' in tag.text) 但我想使用正则表达式模式来提取所需的信息。 有没有办法绕过这个错误?

P.S 我也不能在这段 HTML 上使用sneaker_info.find('td', string=re.compile(r'Size'))

【问题讨论】:

  • 尝试使用 str(re.compile(r'Size'))
  • @Luiz 你认为那会怎样?
  • 转成字符串,只是猜测,想帮忙

标签: python regex beautifulsoup


【解决方案1】:

re.compile() 生成的正则表达式对象与字符串的 in 关键字不兼容,因为它希望接收字符串而不是正则表达式对象。

您可以使用"sm" in "small" =&gt; true,但不能使用1 in "small"。

你可能想要这样的东西:

re.compile('Size').search(tag.text)

在此处查看正则表达式文档以获取更多信息: https://docs.python.org/3/library/re.html

选项 2: 您实际上并不需要这里的正则表达式。对于简单的子字符串匹配来说,这太过分了。 你也可以更简单地做

"Size" in tag.text

【讨论】:

  • 根据我对文档的阅读,我认为他们希望使用 search() 而不是 match() 来实现与 in 等效的行为。
  • @DaveCosta 谢谢,你是正确的更新。
  • 谢谢!!!你真的帮助了我
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多