爬取微信公众号文章中的图片

import requests
from bs4 import BeautifulSoup
import os

def getHtmlText(url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        r = requests.get(url, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
        return ""

def getimgUrl(html, base_url):
    soup = BeautifulSoup(html, "html.parser")
    adlist = []
    for img_tag in soup.find_all("img"):
        try:
            src = img_tag.get("data-src") or img_tag.get("src")
            if src:
                if not src.startswith("http"):
                    src = requests.compat.urljoin(base_url, src)
                adlist.append(src)
        except Exception as e:
            print(f"Error processing image tag: {e}")
            continue
    return adlist

def download(adlist):
    root = r'C:\Users\LiuYang\Desktop\p1\\'
    if not os.path.exists(root):
        os.makedirs(root)

    for i, url in enumerate(adlist):
        path = os.path.join(root, f"{i:02d}.jpg")
        if not os.path.exists(path):
            try:
                r = requests.get(url)
                r.raise_for_status()
                with open(path, 'wb') as f:
                    f.write(r.content)
                print(f"Downloaded: {url}")
            except requests.exceptions.RequestException as e:
                print(f"Failed to download {url}: {e}")

def main():
    url = 'https://mp.weixin.qq.com/s/WQg5qtz7LGpsx6WXuTwk7A'
    html = getHtmlText(url)
    if html:
        img_list = getimgUrl(html, url)
        download(img_list)
        print("Download complete!")
    else:
        print("Failed to retrieve the webpage.")

main()
 

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值