靓汤订单搜索

2024-03-28 18:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在抓取一系列非常扁平的网页,其中对我来说很重要的结构是我想找到出现在具有已知id的h2元素之后的所有元素。我想在这个h2元素之后找到的元素是pblockquote,和{}。排序很重要,在定位这些元素时需要保留。我还应该说,所有感兴趣的元素都是兄弟姐妹,在同一个组织级别上,紧挨着另一个。我该怎么做?在

我试了一下:

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。我也试过了:

^{pr2}$

但这引发了一个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导航模式中找到它们?在


Tags: thetextinpyid元素lineh2
1条回答
网友
1楼 · 发布于 2024-03-28 18:23:17

当您调用h.next_sibling时,beauthoulsoup将返回同一级别下一个元素。现在,这个元素可以是标记,也可以是独立的字符串。我的猜测是,在您要查找的HTML标记之前,您的HTML文档中有一些独立的字符串。在

示例:

html = '<h1>A header</h1>Some random text<p>A paragraph</p>'
soup = BeautifulSoup(html)
h = soup.find('h1') # Contains <h1>A header</h1>
print(h.next_sibling) # Prints u'Some random text', not the p tag

相关问题 更多 >