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

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

soup.prettify()

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

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


当前回答

下面是一个代码片段

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

在我试图刮谷歌的时候也发生过。 我最终使用了pyquery。 安装:

pip install pyquery

Use:

from pyquery import PyQuery    
pq = PyQuery('<html><body><div id="articlebody"> ... </div></body></html')
tag = pq('div#articlebody')

通过id查找元素:

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

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

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