1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 利用beautifulsoup爬取微博搜素朋友圈背景图

利用beautifulsoup爬取微博搜素朋友圈背景图

时间:2022-12-22 11:59:38

相关推荐

利用beautifulsoup爬取微博搜素朋友圈背景图

利用beautifulsoup爬取微博搜素"朋友圈背景图"

微博搜索:朋友圈背景图

1.首先先导入库

requests是用来请求返回网页源代码所需要的请求库,etree和beautifulsoup则是beautifulsoup所需要用到的解析库,os是保存图片所需要用到的库,re是正则表达式用到的库

from lxml import etreeimport requestsfrom bs4 import BeautifulSoupimport osimport re

2.然后写个返回网页源代码的函数get_one_page

函数传递进去的url是我们所要爬取的网页的网址,headers是用来模拟浏览器访问网站,response是是网页返回的信息

当返回的响应状态码等于200时,说明请求成功,就返回网页的源代码

def get_one_page(url): headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}response=requests.get(url,headers=headers)if response.status_code==200:return response.textreturn None

3.接着写一个解析页面,提取我们所需要的信息的函数parse_one_page

通过查看网页源代码,发现所有的图片都在class='card-wrap’的class='m3’的li中的img标签里面,card-wrap是每一条微博的盒子的类名,m3是ul的类名

由此,我们只需要把每个m3里的li中的img提取出来就可以获得图片的链接,接下来通过beautifulsoup把每个img标签都给提取出来,然后通过正则表达式把uid(用户的id)和pic_id(图片的id)从img中提取出来,放进yield中返回

def parse_one_page(html):soup=BeautifulSoup(html,'lxml')items=soup.find_all(class_='card-wrap')for item in items:nr1=item.find_all(name='ul',class_='m3')for nr2 in nr1:image=nr2.select('li > img')for image2 in image:img=image2['src']action_data=image2['action-data']uid=re.search('uid=(\d+)&',action_data).group(1)pic_id=re.search('pic_id=(.*)',action_data).group(1)yield{'img':img,'uid':uid,'pic_id':pic_id}

4.接着写一个保存图片的函数save_img

root_path是保存文件的目录,然后通过os将图片写入目录的文件夹里

def save_img(item):root_path=r'C:\Users\HASEE\微博背景图'uid=item['uid']pic_id=item['pic_id']img=item['img']img_name=pic_id+'.jpg'img_path=root_path+r'\{0}'.format(img_name)if not os.path.exists(root_path):os.makedirs(root_path)if not os.path.exists(img_path):r = requests.get('http:'+img)with open(img_path, 'wb') as f:f.write(r.content)f.close()print(uid+'的'+pic_id+"文件保存成功")else:print("文件已存在")

5.最后写一个主函数main

从网址中可以发现,每一页都是通过网址最后的page改变,所以爬取页数只需要改page的值就可以搞定

首先先写一个循环,循环输入每一页的url,通过调用上面写的get_one_page函数,获得每页的网页源代码并赋值给html,然后通过parse_one_page函数将每一页的图片链接都提取出来,最后调用save_img函数将图片下载下来

def main():x=0for i in range(10):url='/weibo/%25E6%259C%258B%25E5%258F%258B%25E5%259C%2588%25E8%2583%258C%25E6%2599%25AF%25E5%259B%25BE?topnav=1&wvr=6&page='+str(i)html=get_one_page(url)for item in parse_one_page(html):x=x+1print('第'+str(x)+'张')save_img(item)

6.所有步骤都已经完成,最后通过main()启动主函数就可以爬取朋友圈背景图了

main()

ps:这是我学习完爬虫第一次发帖,对于很多名词性的东西也是经常记混,如果发现啥错误请告诉我,我立马改正

ps:不知道为什么会重复爬取一遍,我一下子没想明白是咋回事,要是大佬知道,请教教我

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。