Python使用requests与BeautifulSoup抓取One推送图文内容
本文详解如何利用Python的requests库获取网页数据,结合BeautifulSoup解析HTML结构,提取One推送的文字与图片链接。通过封装下载函数并遍历DOM节点,实现自动化获取每日图文内容并保存至本地,为Python网络爬虫初学者提供完整代码示例与操作参考。
Python抓取One推送图文实战
本文主要演示如何使用Python的requests库抓取One推送中的文字与图片内容,并提供详细的代码示例。该方案对希望学习网络爬虫或需要自动化获取此类信息的读者具有实际的参考价值。
requests是Python中广泛使用的第三方HTTP库,基于urllib构建,采用Apache2 Licensed开源协议。相比原生的urllib,requests提供了更简洁的API,能大幅简化HTTP测试与数据获取的工作量。以下将具体记录其使用方法及结合解析库的完整流程:
核心代码实现与解析
from bs4 import BeautifulSoup
from lxml import html
import xml
import requests
#下载图片函数
def download_img(url,name):
""""
下载指定url的图片
url:图片的url;
name:保存图片的名字
"""
try:
respone = requests.get(url)
f_img = respone.content
path = r'C:\Users\86131\Desktop\itchat\send_file\images\\%s.jpg'%(name)
with open(path, "wb")as f:
f.write(f_img)
except Exception as e:
print("---------地址出错------------")
url_list = []
f = requests.get("http://wufazhuce.com/")
# #打印网页内容
# print(f.content.decode())
soup = BeautifulSoup(f.content,"lxml")
try:
first_div = soup.find("div",attrs={'id':'main-container'}).find('div',attrs={'class':'carousel-inner'})
a_all = first_div.find_all('a')
for i in a_all:
url_list.append(i.attrs['href'])
except Exception as e:
print("---------出错------------")
#得到one的首页推荐页面
f_1 = requests.get(url_list[0])
#打印网页内容
# print(f_1.content.decode())
soup_1 = BeautifulSoup(f_1.content,"lxml")
try:
second_div = soup_1.find("div",attrs={'id':'main-container'}).find('div',attrs={'class':'one-cita-wrapper'})
third_div = soup_1.find("div",attrs={'id':'main-container'}).find('div',attrs={'class':'one-imagen'})
#获得时期值
now_month = second_div.find('p',attrs={'class':'may'}).text
now_one_day = second_div.find('p',attrs={'class':'dom'}).text
#获得图片的url
img_url = third_div.find('img').attrs['src']
#获得一段话并去除开头的空格
one_text = second_div.find("div",attrs={'class':'one-cita'}).text.strip()
#将获得日期拼接
now_day = now_one_day +' '+ now_month
#调用函数下载图片
download_img(img_url, now_day)
except Exception as e:
print("---------出错------------")
上述代码展示了完整的抓取逻辑,包括初始化请求、解析页面结构、提取图文链接以及执行本地下载操作。开发者可根据实际需求调整保存路径或异常处理逻辑,该示例可直接用于学习或集成到更大的项目中。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













