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

2024-04-18 15:50:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经启动并运行了Beautifulsoup,但是在解析网站的html时,我的目标是“soup”对象似乎没有显示div中的div等等。我试图从一个网站,这是许多层深的项目细节。当查看实际的站点html时,我可以看到我想要到达的层,但是soup只显示父div,如下所示:

<div id="react-views-container"></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")

Tags: importdividsupport网站requestcontainerhtml
1条回答
网友
1楼 · 发布于 2024-04-18 15:50:45

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

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

当您希望divdiv内部时,这种方法非常有效

你甚至可以用这个

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=

这是以json格式给出包含项的response。你可以从这里把你的东西报废。你知道吗

无法添加响应,因为它的大小很大,而且我的Google chrome标签开始挂起。但是我已经验证了

相关问题 更多 >