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

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

soup.prettify()

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

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


当前回答

通过id查找元素:

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

其他回答

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"})
soup.find("tagName",attrs={ "id" : "articlebody" })

你喝过汤吗?findAll("div", {"id": "articlebody"})?

听起来很疯狂,但如果你从野外采集东西,你不能排除多次潜水的可能性……

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

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")