【问题标题】:How to find the script src link?(Beautiful Soup)如何找到脚本src链接?(美汤)
【发布时间】:2021-10-18 15:48:55
【问题描述】:
tags = [{tag.name: tag.text.strip()} for tag in soup.find_all('h2')]

返回如下:

[{'h2':'My'},{'h2':'hey'}] # Returns all the h2 elements with their content.

现在我想要上述格式的<script src =''> 内的所有链接。

假设,对于 HTML 代码,

<script src="https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.hvE_rrhCzPE.O/m=gapi_iframes,googleapis_client/rt=j/sv=1/d=1/ed=1/rs=AHpOoo-98F2Gk-siNaIBZOtcWfXQWKdTpQ/cb=gapi.loaded_0" nonce="" async=""></script>

结果应该是

#Both Acceptable

[{'script':'https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.hvE_rrhCzPE.O/m=gapi_iframes,googleapis_client/rt=j/sv=1/d=1/ed=1/rs=AHpOoo-98F2Gk-siNaIBZOtcWfXQWKdTpQ/cb=gapi.loaded_0'}]

OR

[{'script src':'https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.hvE_rrhCzPE.O/m=gapi_iframes,googleapis_client/rt=j/sv=1/d=1/ed=1/rs=AHpOoo-98F2Gk-siNaIBZOtcWfXQWKdTpQ/cb=gapi.loaded_0'}]

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup python-requests


    【解决方案1】:

    您只需将您找到的标签从h2 更改为script。然后,您不需要使用tag.text 获取该元素的文本,而是需要tag['attribute name'] 语法中的属性值。所以像:

    tags = [{tag.name: tag['src']} for tag in soup.find_all('script')]
    

    【讨论】:

      猜你喜欢
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 2021-04-12
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      相关资源
      最近更新 更多