我试着从下面的代码片段中解析评论中的内容,但似乎根本不起作用。我该怎么做?我的目的是获取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
切换到
html.parser
,然后只访问内部的p
标记。你知道吗html.parser
的优点是它不会在soup数据周围添加额外的<html><body>...</body></html>
标记。然后可以使用comment.next_element.p.text
访问p
标记的内容。你知道吗相关问题 更多 >
编程相关推荐