如何使用beautifulsoup访问div的内容?

时间:2019-06-28 13:58:38

标签: python python-3.x web-scraping beautifulsoup

我已经启动并正在运行Beautifulsoup,但是在为网站解析html时,我的目标是“ soup”对象似乎没有显示div中的div等。我试图从多层的网站上获取商品详细信息。当查看实际的html站点时,我可以看到我想要到达的层,但是汤只显示父div,如下所示:

<div id="react-views-container"></div>

我如何进入这个div?

到目前为止,我的代码如下:

import urllib.request
import requests
from bs4 import BeautifulSoup

#setting up connection and testing by printig html
proxy_support = urllib.request.ProxyHandler("proxies_hidden_for_privacy")
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
html = urllib.request.urlopen("target_website").read()
print (html)

soup = BeautifulSoup(html)

div = soup.find(id="react-views-container")

1 个答案:

答案 0 :(得分:2)

您可以在下面的代码中直接传递所需的div ID;

soup.find("div", {"id": "id-you-want"})

当您想将div放在div内时,此方法效果很好

您甚至可以使用它,

soup.find_all('div')

它将为您提供所有div的列表。然后,您可以过滤掉所需的div

编辑::

在分析网站时,我们可以看到它正在动态加载元素(项目),并且可能是通过javascript和某些XHR请求这样做的。

解决方案

如果您使用scrapyselenium,因为它们使用Web驱动程序,因此可以解决此问题,因此使用它们代替BeautifulSoup可以轻松地删除此类网站。

下一种可能的方法是,找到网站为获取项目而调用的URL(XHR / API)。

注意:我即将更新网址

编辑2:

请求

https://www.instacart.com/v3/containers/sprouts/search_v3/milk?source=web&cache_key=38e8f7-7370-t-35b&per=50&tracking.items_per_row=5&tracking.source_url=undefined&tracking.autocomplete_prefix=&tracking.autocomplete_term_impression_id=&tracking.search_bar_impression_event_id=

这将给response包含json格式的项目。您可以从这里废弃您的物品。

因为它很大,并且我的Google chrome标签开始挂起,所以无法添加响应。但我已经证实