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

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

soup.prettify()

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

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


当前回答

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 = BeautifulSoup(:"index.html")
titleList = soup.findAll('title')
divList = soup.findAll('div', attrs={ "class" : "article story"})

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

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

我使用:

soup.findAll('tag', attrs={'attrname':"attrvalue"})

就像我的find/findall语法一样;也就是说,除非在标签和属性列表之间有其他可选参数,否则不应该有什么不同。

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

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