[英]BeautifulSoup and Selenium cannot find div or text on website
[英]Can't find text in li under div using BeautifulSoup
我正在尝试使用 BeautifulSoup 在本网站的 div 下获取 ul 中的文本: https://www.nccn.org/professionals/physician_gls/recently_updated.aspx
但我只得到一个空的div。 我的代码是:
page = requests.get("https://www.nccn.org/professionals/physician_gls/recently_updated.aspx")
soup=BeautifulSoup(page.content,"html.parser")
_div=soup.find("div",{"id":"divRecentlyUpdatedList"})
element = [i.text for i in b.find("a") for b in _div.find("ul")]
结果是:
HTML文件截图如下: div和ul
此外,还有 javascript 出现在我试图从中获取内容的 div 之后:
我也试过像这样得到所有 li:
l = []
for tag in soup.ul.find_all("a", recursive=True):
l.append(tag.text)
但我得到的文字不是我想要的。 javascript 是否隐藏了该 div 下的文本?
欢迎任何帮助。 非常感谢您提前。
内容从端点https://www.nccn.org/professionals/physician_gls/GetRecentlyUpdated.ashx异步填充到 HTML 中,返回 Z0ECD11C1D7A287401F8Z4D。 由于它是通过 JS 异步填充的,因此requests
看不到它的结果。
您可以直接请求该端点并改为解析 JSON,例如:
page = requests.get("https://www.nccn.org/professionals/physician_gls/GetRecentlyUpdated.ashx")
list = json.loads(page.content)
for item in list['recent_guidelines']:
print(item['Name'], item['VersionNumber'], item['PublishedDate'])
问题实际上与您猜想的相反:在 API 调用之后, <div id="divRecentlyUpdatedList">
中的内容被 Javascript 填充。
使用requests.get
时,任何 Javascript 都不会在网站上执行,因此我们最终会得到一个空的 div。 为此,您需要使用一个使用无头浏览器的库,以便可以执行 Javascript - 例如requests-html
:
from requests_html import HTMLSession
from bs4 import BeautifulSoup
URL = "https://www.nccn.org/professionals/physician_gls/recently_updated.aspx"
session = HTMLSession()
site = session.get(URL)
site.html.render()
html = site.html.html
soup = BeautifulSoup(html, 'html.parser')
_div=soup.find("div",{"id":"divRecentlyUpdatedList"})
现在在_div
中,您将获得来自 API 的渲染内容,您可以继续查找所需的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.