![](/img/trans.png)
[英]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.