soup.find("tagName", { "id" : "articlebody" })

为什么不返回<div id="articlebody">…</div>标签和东西之间?它什么也不返回。我知道它的存在因为我正盯着它

soup.prettify()

汤。Find ("div", {"id": "articlebody"})也不起作用。

(编辑:我发现BeautifulSoup没有正确解析我的页面,这可能意味着我试图解析的页面在SGML或其他中没有正确格式化)


当前回答

在beautifulsoup源代码中,这一行允许在div中嵌套div;所以你对卢卡斯评论的担心是没有根据的。

NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']

我认为您需要做的是指定您想要的attrs,例如

source.find('div', attrs={'id':'articlebody'})

其他回答

你应该发布你的示例文档,因为代码运行良好:

>>> import BeautifulSoup
>>> soup = BeautifulSoup.BeautifulSoup('<html><body><div id="articlebody"> ... </div></body></html')
>>> soup.find("div", {"id": "articlebody"})
<div id="articlebody"> ... </div>

找到<div>s内<div>s工作以及:

>>> soup = BeautifulSoup.BeautifulSoup('<html><body><div><div id="articlebody"> ... </div></div></body></html')
>>> soup.find("div", {"id": "articlebody"})
<div id="articlebody"> ... </div>

通过id查找元素:

div = soup.find(id="articlebody")

下面是一个代码片段

soup = BeautifulSoup(:"index.html")
titleList = soup.findAll('title')
divList = soup.findAll('div', attrs={ "class" : "article story"})

正如你所看到的,我找到了所有的标签,然后我找到了所有的标签class="article"在里面

很可能是因为默认的beautifulsoup解析器有问题。换一个不同的解析器,比如'lxml',然后再试一次。

from bs4 import BeautifulSoup
from requests_html import HTMLSession

url = 'your_url'
session = HTMLSession()
resp = session.get(url)

# if element with id "articlebody" is dynamic, else need not to render
resp.html.render()

soup = bs(resp.html.html, "lxml")
soup.find("div", {"id": "articlebody"})