【问题标题】:Can't parse some text within comment无法解析评论中的某些文本
【发布时间】:2018-02-15 08:13:25
【问题描述】:

我试图从下面的 sn-p 解析评论中的内容,但它似乎根本不起作用。我怎样才能让它工作?我的意图是获取 p 标记内的文本,输出应为:

Hi there!!
Hi again!!

我已经尝试过的脚本:

from bs4 import BeautifulSoup, Comment

content="""
<!-- comment --><a href="https://extratorrent.ag/"><p>Hi there!!</p></a>
<!-- comment1 --><a href="https://thepiratebay.se/"><p>Hi again!!</p></a>
"""
soup = BeautifulSoup(content, 'lxml')
for comment in soup.find_all(string=lambda text:isinstance(text,Comment)):
    data = BeautifulSoup(comment.next_element,"lxml")
    for item in data.select("p"):
        print(item.text)

我遇到的错误:

Traceback (most recent call last):
  File "C:\AppData\Local\Programs\Python\Python35-32\Social.py", line 9, in <module>
    data = BeautifulSoup(comment.next_element,"lxml")
  File "C:\AppData\Local\Programs\Python\Python35-32\lib\site-packages\bs4\__init__.py", line 191, in __init__
    markup = markup.read()
TypeError: 'NoneType' object is not callable

【问题讨论】:

  • 发布错误的完整回溯

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

切换到html.parser,然后直接访问里面的p标签。

html.parser 的优点是它不会在你的汤数据周围添加额外的&lt;html&gt;&lt;body&gt;...&lt;/body&gt;&lt;/html&gt; 标签。然后,您可以使用comment.next_element.p.text 访问p 标记的内容。

soup = BeautifulSoup(content, 'html.parser')
for comment in soup.find_all(string=lambda text: isinstance(text, Comment)):
    print(comment.next_element.p.text)

Hi there!!
Hi again!!

【讨论】:

  • 哇!这是一个传奇的修复。系统不允许我在时间到来之前接受你的回答。已经加了一个。非常感谢。
  • @novice-coder 不客气!尽管您可能希望确保您的代码不会在注释没有被锚标记或 p 标记成功时出错。 (想想,try...except)祝你好运!
猜你喜欢
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 2012-11-01
相关资源
最近更新 更多