soup.find("tagName", { "id" : "articlebody" })
为什么不返回<div id="articlebody">…</div>标签和东西之间?它什么也不返回。我知道它的存在因为我正盯着它
soup.prettify()
汤。Find ("div", {"id": "articlebody"})也不起作用。
(编辑:我发现BeautifulSoup没有正确解析我的页面,这可能意味着我试图解析的页面在SGML或其他中没有正确格式化)
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"})
其他回答
你喝过汤吗?findAll("div", {"id": "articlebody"})?
听起来很疯狂,但如果你从野外采集东西,你不能排除多次潜水的可能性……
我认为'div'标签嵌套太多是有问题的。我试图从facebook html文件解析一些联系人,Beautifulsoup无法找到带有类“fcontent”的标签“div”。
其他类也会发生这种情况。当我搜索div时,它只搜索那些嵌套不多的div。
html源代码可以是任何页面从facebook的朋友列表的一个朋友的你(不是你的一个朋友)。如果有人能测试它并给出一些建议,我会非常感激。
这是我的代码,我只是试图用类“fcontent”打印标签“div”的数量:
from BeautifulSoup import BeautifulSoup
f = open('/Users/myUserName/Desktop/contacts.html')
soup = BeautifulSoup(f)
list = soup.findAll('div', attrs={'class':'fcontent'})
print len(list)
我使用:
soup.findAll('tag', attrs={'attrname':"attrvalue"})
就像我的find/findall语法一样;也就是说,除非在标签和属性列表之间有其他可选参数,否则不应该有什么不同。
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")
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"})