【问题标题】:Can't find text in li under div using BeautifulSoup使用 BeautifulSoup 在 div 下的 li 中找不到文本
【发布时间】:2020-09-10 09:46:26
【问题描述】:

我正在尝试使用 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 and ul

另外,在我试图从中获取内容的 div 之后有 javascript:

div and javascript

我也试过这样获取所有的 li:

l = []
for tag in soup.ul.find_all("a", recursive=True): 
    l.append(tag.text)

但我得到的文字不是我想要的。该div下的文本是否被javascript隐藏了?

欢迎任何帮助。非常感谢您。

【问题讨论】:

  • 您要提取的文本是什么?

标签: javascript python web-scraping beautifulsoup


【解决方案1】:

问题其实和你猜的正好相反:<div id="divRecentlyUpdatedList"> 里面的内容在 API 调用之后被 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 的渲染内容,您可以继续找到您想要的内容。

【讨论】:

    【解决方案2】:

    内容从端点 https://www.nccn.org/professionals/physician_gls/GetRecentlyUpdated.ashx 异步填充到 HTML 中,该端点返回 JSON。由于它是通过 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'])
    

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      相关资源
      最近更新 更多