【问题标题】:How do I scrape img tags from 1mg webaite如何从 1mg 网站上抓取 img 标签
【发布时间】:2020-12-14 23:51:02
【问题描述】:

我正在尝试从1mg 网站抓取网页的 HTML。

在 URL 中,当我尝试将其保存为 HTML 时,或者当我尝试使用 BeautifulSoup 抓取它时,我得到了 None 返回。

用于抓取的代码:

from bs4 import BeautifulSoup
import requests
headers = {"User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'}
url='https://www.1mg.com/categories/ayurveda/top-brands-265?filter=true&brand=Dabur'
page= requests.get(url, headers=headers)
soup=BeautifulSoup(page.content,'html.parser')
img=soup.find_all('img',{'class':'style__image___Ny-Sa style__loaded___22epL'})
for i in img:
 i['src']

这是要抓取的图像的示例标记:

 <img alt="Dabur Shilajit Gold Capsule" src="https://res.cloudinary.com/du8msdgbj/images/w_150,h_150,c_fit,q_auto,f_auto/v1603435745/feaoalhp4c6bv8icllgp/dabur-shilajit-gold-capsule.jpg" title="Dabur Shilajit Gold Capsule" class="style__image___Ny-Sa style__loaded___22epL">

我以手动复制上述标签为例。我对产品名称和价格使用了相同的代码(更改了标签),它运行良好。我什至尝试使用 img 标签的父标签。

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案1】:

    页面是动态加载的,所以requests 不支持。不过网站上有JSON格式的数据,尝试使用内置的json模块获取所有图片(共40张)。

    import json
    import requests
    from bs4 import BeautifulSoup
    
    URL = "https://www.1mg.com/categories/ayurveda/top-brands-265?filter=true&brand=Dabur"
    
    soup = BeautifulSoup(requests.get(URL).content, "html.parser")
    json_data = json.loads(
        soup.select_one("#content-container > div > div > div > script:nth-child(5)").string
    )
    
    for data in json_data["itemListElement"]:
        print(data["image"])
    

    输出:

    https://res.cloudinary.com/du8msdgbj/images/w_150,h_150,c_fit,q_auto,f_auto/v1603435745/feaoalhp4c6bv8icllgp/dabur-shilajit-gold-capsule.jpg
    https://res.cloudinary.com/du8msdgbj/images/w_150,h_150,c_fit,q_auto,f_auto/v1500611141/wwkoja9giavml3tgyza4/dabur-musli-pak-laghu.jpg
    ..All the way until
    
    https://res.cloudinary.com/du8msdgbj/images/w_150,h_150,c_fit,q_auto,f_auto/v1601446598/sujrsvjyzcuvpfwtekhz/anti-oxidants-combo-of-organic-india-tulsi-ginger-turmeric-25-tea-bag-and-dabur-honey-squeezy-225gm-buy-1-get-1-free.png
    

    【讨论】:

      猜你喜欢
      • 2011-08-02
      • 2018-12-08
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 2016-09-08
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多