【问题标题】:escaped string is not recognized转义字符串无法识别
【发布时间】:2018-05-10 10:49:08
【问题描述】:

我正在使用 python、requests 和 BeautifulSoup 构建一个网络抓取应用程序。

我将一个类变量声明为:

class myClass(object):
    TAG = "\"span\",{\"data-automation\":\"jobListingDate\"}"

我使用 print self.TAG 验证了这个 TAG

我从print self.TAG 得到的输出是"span",{"data-automation":"jobListingDate"},这表明self.TAG 与此字符串"span",{"data-automation":"jobListingDate"} 相同

但是下面两行代码产生了不同的结果:

  • r = requests.get("someURL")
  • html = BeautifulSoup(r.content, "html.parser")
  • html.find(self.TAG) #this line does not find anything at all
  • html.find("span",{"data-automation":"jobListingDate"}) #this line does find what I am after

我一头雾水,self.TAG怎么和"span",{"data-automation":"jobListingDate"}这个字符串不一样,我是不是没有正确转义?

【问题讨论】:

  • 什么是selfhtml.find 是什么?
  • @cᴏʟᴅsᴘᴇᴇᴅ,问题已解决。仍然感谢您的评论,我应该从一开始就澄清它们。

标签: python beautifulsoup request


【解决方案1】:

html.find(self.TAG) 的情况下,您实际上只是将单个字符串作为参数,即:

html.find('"span",{"data-automation":"jobListingDate"}')

注意字符串周围的单引号',与"\"span\",{\"data-automation\":\"jobListingDate\"}"相同

在您的第二个示例html.find("span",{"data-automation":"jobListingDate"}) 中,我们谈论的是两个参数。

当然这会有不同的表现。

【讨论】:

  • 谢谢,我用type()查看html和self.TAG是不是同一个类型,然后发现有问题,和你说的完全一样。
猜你喜欢
  • 2014-08-01
  • 1970-01-01
  • 2015-08-24
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 2013-02-17
  • 2019-02-18
相关资源
最近更新 更多