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

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

soup.prettify()

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

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


当前回答

Beautiful Soup 4使用.select()方法支持大多数CSS选择器,因此你可以使用id选择器,例如:

soup.select('#articlebody')

如果你需要指定元素的类型,你可以在id选择器之前添加一个类型选择器:

soup.select('div#articlebody')

.select()方法将返回一个元素集合,这意味着它将返回与下面的.find_all()方法示例相同的结果:

soup.find_all('div', id="articlebody")
# or
soup.find_all(id="articlebody")

如果你只想选择一个元素,那么你可以使用.find()方法:

soup.find('div', id="articlebody")
# or
soup.find(id="articlebody")

其他回答

下面是一个代码片段

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

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

Beautiful Soup 4使用.select()方法支持大多数CSS选择器,因此你可以使用id选择器,例如:

soup.select('#articlebody')

如果你需要指定元素的类型,你可以在id选择器之前添加一个类型选择器:

soup.select('div#articlebody')

.select()方法将返回一个元素集合,这意味着它将返回与下面的.find_all()方法示例相同的结果:

soup.find_all('div', id="articlebody")
# or
soup.find_all(id="articlebody")

如果你只想选择一个元素,那么你可以使用.find()方法:

soup.find('div', id="articlebody")
# or
soup.find(id="articlebody")

Id属性总是唯一标识的。这意味着您甚至不需要指定元素就可以直接使用它。因此,如果您的元素有它来解析内容,这是一个加分项。

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

很可能是因为默认的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"})