我正在抓取一系列非常扁平的网页,其中对我来说很重要的结构是我想找到出现在具有已知id的h2
元素之后的所有元素。我想在这个h2
元素之后找到的元素是p
,blockquote
,和{
我试了一下:
soup = BeautifulSoup(response)
# here is the title
h = soup.find("h2", {"id":"content"})
print(h.text) # correct, so we're in the right place
print(h.next_sibling)
但是最后的print语句只打印一个None
。我也试过了:
但这引发了一个NavigableString错误:
Traceback (most recent call last):
File "scrape.py", line 15, in <module>
print(i.text)
File "/usr/lib/python2.7/dist-packages/BeautifulSoup.py", line 473, in __getattr__
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
AttributeError: 'NavigableString' object has no attribute 'text'
我要查找的元素绝对与这个h2
元素处于同一级别,并且出现在HTML的后面。如何在BS导航模式中找到它们?在
当您调用
h.next_sibling
时,beauthoulsoup将返回同一级别下一个元素。现在,这个元素可以是标记,也可以是独立的字符串。我的猜测是,在您要查找的HTML标记之前,您的HTML文档中有一些独立的字符串。在示例:
相关问题 更多 >
编程相关推荐