【问题标题】:Isolating script with BeautifulSoup用 BeautifulSoup 隔离脚本
【发布时间】:2020-07-10 12:29:27
【问题描述】:

我已经在 BeautifulSoup 中加载了整个 HTML 页面。有什么方法可以隔离这个字典集合吗?

  • 类型(黄色)在页面中只出现一次,没有重复

这是我用来导入HTML文件的代码(不能使用urllib):from bs4 import BeautifulSoup

with open('/content/drive/My Drive/Colab Notebooks/Projects/20200710_StreetEasy_WebScraping/1.html') as f:
  contents = f.read()
  soup = BeautifulSoup(contents, 'lxml')
print(soup)

搜索 a 标签返回输出

a = soup.find_all('a')
a
[<a class="html-attribute-value html-resource-link" href="https://cdn-assets-s3.streeteasy.com/assets/manifest-c93475b02bd2409b4a52e21af023e5d5f489f19500d234a3660fe4d35069bbac.json" rel="noreferrer noopener" target="_blank">//cdn-assets-s3.streeteasy.com/assets/manifest-c93475b02bd2409b4a52e21af023e5d5f489f19500d234a3660fe4d35069bbac.json</a>,
 <a class="html-attribute-value html-resource-link" href="https://browser.sentry-cdn.com/5.19.0/bundle.min.js" rel="noreferrer noopener" target="_blank">https://browser.sentry-cdn.com/5.19.0/bundle.min.js</a>,
 <a class="html-attribute-value html-resource-link" href="https://cdn-assets-s3.streeteasy.com/assets/jquery-fe1be651ec56a9cc875a437f09db5b175cc6acf4b911bed0ef265955a099db55.js" rel="noreferrer noopener" target="_blank">//cdn-assets-s3.streeteasy.com/assets/jquery-fe1be651ec56a9cc875a437f09db5b175cc6acf4b911bed0ef265955a099db55.js</a>,
...

搜索脚本标签不返回任何输出

import re
scripts = soup.find_all("script")
scripts
[]

也许我在导入文档时做错了什么?

【问题讨论】:

  • 您介意在 Markdown 中发布该输出而不是包含 png 吗? stackoverflow.com/editing-help
  • 刚尝试导入html代码显示不清晰,无法设置缩进

标签: python html beautifulsoup


【解决方案1】:

您可以使用find_all 中的string 参数来过滤包含@context JSON 的脚本标签

scripts = soup.find_all("script", string=re.compile("@context"))

然后遍历您的scripts 并在删除//&lt;![CDATA[//]] 后加载JSON

【讨论】:

  • 试过了还是不行,我在问题里加了细节
【解决方案2】:

假设你做过类似的事情

soup = BeautifulSoup(html, 'lxml')

您可以使用 BeautifulSoup 的 find() https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find 隔离该特定元素

script = soup.find("script", {"type" : "application/ld+json"})

【讨论】:

  • 试过了还是不行,我在问题里加了细节
猜你喜欢
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 2021-12-24
  • 1970-01-01
  • 2016-02-12
  • 2015-04-08
  • 1970-01-01
相关资源
最近更新 更多