菜菜子nn 2022-01-12 23:15 采纳率: 83.3%
浏览 42
已结题

请问beautifulsoup里面怎么拼接网址呀?

就是因为这个爬取的网站他有一个主url,然后里面的子页面源代码都是后面不一样,想着怎么让他们拼接起来,我自己的代码如下,求指点

import requests
from bs4 import BeautifulSoup
import time
url = "https://www.umei.cc/p/gaoqing/"
resp = requests.get(url)
resp.encoding = "utf-8"
# print(resp.text)
# 把源代码交给BS4
main_page = BeautifulSoup(resp.text, "html.parser")
alist = main_page.find("div", class_="TypeList").find_all("a")

# print(alist)
for a in alist:
    href = a.get('href')  # 直接通过get拿到属性的值
    #拿到子页面的源代码
    child_page_resp = requests.get(href)
    child_page_resp.encoding = 'utf-8'
    child_page_text = child_page_resp.text
    # 从子页面中拿到图片的下载链接
    child_page = BeautifulSoup(child_page_text, "html.parser")
    p = child_page.find("div", id_="ArticleId")
    img = p.find("img")
    print(img.get("src"))
    #下载图片
    img_resp = requests.get(src)
    # img_resp.content  # 这里拿到的是字节,字节写到文件里不就是图片嘛
    img_name = src.split("/")[-1]  #拿到url中最后一个/以后的内容
    with open("img/"+img_name, mode="wb") as f:
        f.write(img_resp.content) #图片内容写入文件
    print("over!", img_name)
    time.sleep(1)
print("all over")

  • 写回答

2条回答 默认 最新

  • 猫猫爱吃鱼 2022-01-13 11:16
    关注
    import requests
    from bs4 import BeautifulSoup
    import time
    url = "https://www.umei.cc/p/gaoqing/"
    resp = requests.get(url)
    resp.encoding = "utf-8"
    # print(resp.text)
    # 把源代码交给BS4
    main_page = BeautifulSoup(resp.text, "html.parser")
    alist = main_page.find("div", class_="TypeList").find_all("a")
    # print(alist)
    for a in alist:
        href = ‘{0}/{1}'.format(url, a.get('href'))
        #拿到子页面的源代码
        child_page_resp = requests.get(href)
        child_page_resp.encoding = 'utf-8'
        child_page_text = child_page_resp.text
        # 从子页面中拿到图片的下载链接
        child_page = BeautifulSoup(child_page_text, "html.parser")
        p = child_page.find("div", id_="ArticleId")
        img = p.find("img")
        src = '{0}/{1}'.format(url, img.get("src"))
        #下载图片
        img_resp = requests.get(src)
        # img_resp.content  # 这里拿到的是字节,字节写到文件里不就是图片嘛
        img_name = src.split("/")[-1]  #拿到url中最后一个/以后的内容
        with open("img/"+img_name, mode="wb") as f:
            f.write(img_resp.content) #图片内容写入文件
        print("over!", img_name)
        time.sleep(1)
    print("all over")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月21日
  • 已采纳回答 1月13日
  • 创建了问题 1月12日

悬赏问题

  • ¥15 链接问题 C++LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接