【问题标题】:Unable to find text although it is present尽管存在文本,但无法找到它
【发布时间】:2016-09-05 14:35:56
【问题描述】:

我正在学习使用 Python 进行网络抓取。我编写了从印度黄页之一检索公司名称的代码

r =  requests.get("http://xyzxyz", headers={'User-Agent' : "Magic Browser"})
soup= BeautifulSoup(r.content,"html.parser")

for link in soup.findAll("div", {"class" : "col-sm-5"}):
    coLink = link.find("span" , {"class" : "jcn"})
    companyName = coLink.find("a").text

我收到错误“AttributeError: 'NoneType' object has no attribute 'find'”。我知道如果对象没有找到任何东西,我们会得到这个错误。但是,如果当我打印(coLink)时,它会在每个跨度类中提供以下链接

<span class="jcn"><a href="http://xyz/Kolkata/Sunrise-International-&lt;near&gt;-B-R-B-Basu-Road-/033P3001041_BZDET?xid=S29sa2F0YSBUYXBlciBSb2xsZXIgQmVhcmluZyBEZWFsZXJz" onclick="_ct('clntnm', 'lspg');" title="Sunrise International in , Kolkata">Sunrise International</a>
</span>
<span class="jcn"><a href="http://xyz/Kolkata/Shree-Shakti-Vyapaar-PVT-LTD/033P6001995_BZDET?xid=S29sa2F0YSBUYXBlciBSb2xsZXIgQmVhcmluZyBEZWFsZXJz" onclick="_ct('clntnm', 'lspg');" title="Shree Shakti Vyapaar PVT LTD in , Kolkata">Shree Shakti Vyapaar PVT LTD</a>
</span>

你能帮忙如何获取公司的文本吗?

【问题讨论】:

  • 您确定所有span.jcn 标签都包含在a 标签内吗?
  • 所以添加简单的异常将通过忽略所有没有标签的 span.jcn 来解决这个问题?
  • 在任何情况下,你应该先检查,如果coLink.find("a")返回一个你可以获取文本的标签,或者它返回None
  • @ChristosPapoulas 正如我在问题中提到的,我已经尝试过 print(colink)。我还提供了该打印的输出。你可以在输出中看到“a”在那里。
  • 不错!记得给cmets点赞!谢谢

标签: python web-scraping beautifulsoup find


【解决方案1】:

不解释当前问题,但提供替代解决方案 - 您可以使用与所需 a 元素匹配的 CSS selector

for link in soup.select(".col-sm-5 .jcn a"):
    print(link.get_text())

这样,如果span 内部没有a 链接,您将不会收到任何错误。

请注意,col-sm-5 是用于定位元素的糟糕类名 - 它是特定于 UI/布局的,并且很有可能被更改。

【讨论】:

  • 更正代码中的小语法后: r = requests.get("justdial.com/Kolkata/Taper-Roller-Bearing-Dealers", headers={'User-Agent' : "Magic Browser"}) soup= BeautifulSoup(r.content ,"html.parser") for link in soup.select({".col-sm-5 .jcn a"}): print(link.get_text()) 现在它给出了“'set'对象没有属性'read '"。
  • @BhaveshGhodasara 是的,修正了错字。但是您遇到的这个错误与提供的代码无关。
  • 回溯(最近一次调用最后一次):文件“g:\pyt\justdial.py”,第 15 行,在 中,用于 soup.select({".col-sm-5 .jcn a"}):文件“C:\Users\user\AppData\Local\Programs\Python\Python35\lib\site-packages\bs4\element.py”,第 1349 行,在选择标记 = shlex.split(选择器)文件“C:\Users\user\AppData\Local\Programs\Python\Python35\lib\shlex.py”,第 273 行,拆分返回列表(lex)文件“C:\Users\user\AppData\Local \Programs\Python\Python35\lib\shlex.py",第 263 行,在 next 中 token = self.get_token() 文件
  • “C:\Users\user\AppData\Local\Programs\Python\Python35\lib\shlex.py”,第 90 行,在 get_token raw = self.read_token() 文件“C:\ Users\user\AppData\Local\Programs\Python\Python35\lib\shlex.py",第 118 行,在 read_token nextchar = self.instream.read(1) AttributeError: 'set' object has no attribute 'read' .. ......它只显示for循环。
  • @BhaveshGhodasara 啊,当然,你已经把错字改错了,去掉花括号。再次抱歉打错了。
猜你喜欢
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2021-09-22
  • 2019-08-01
  • 1970-01-01
相关资源
最近更新 更多