python爬取百度贴吧图片库_案例关于python百度贴吧图片爬取教程!

本文介绍了一个使用Python和lxml库爬取百度贴吧图片的教程。通过发送HTTP请求,解析HTML,提取图片链接并下载到本地。代码示例包括设置User-Agent,定义请求函数,解析页面获取图片链接,以及下载保存图片的方法。
摘要由CSDN通过智能技术生成

抓取百度贴吧的的图片,网址:百度贴吧

直接上代码:

# -*- coding:utf-8 -*-

from lxml import etree

import requests

class TiebaSpider(object):

def __init__(self, tieba_name, begin_page, end_page):

self.headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"}

self.base_url = "https://tieba.baidu.com"

self.tieba_name = tieba_name

self.begin_page = int(begin_page)

self.end_page = int(end_page)

def send_request(self, url, params ={}):

try:

html = requests.get(url, params = params, headers = self.headers).content

return html

except Exception, err:

print err

def load_page(self, html):

html_obj = etree.HTML(html)

link_list = html_obj.xpath("//div[@class='t_con cleafix']/div/div/div/a/@href")

for link in link_list:

html = self.send_request(self.base_url + link)

self.load_image(html)

def load_image(self, html):

html_obj = etree.HTML(html)

link_list = html_obj.xpath("//img[@class='BDE_Image']/@src")

for link in link_list:

data = self.send_request(link)

self.write_image(data, link[-11:])

def write_image(self, data, filename):

print "[INFO]: 正在下载%s..." % filename

with open(u"D:\图片\哈哈\pp" + filename, "wb") as f:

f.write(data)

def start_work(self):

for page in range(self.begin_page, self.end_page + 1):

pn = (page - 1) * 50

keyword = {"kw" : self.tieba_name, "pn" : pn}

html = self.send_request(self.base_url + "/f?", keyword)

self.load_page(html)

if __name__ == "__main__":

tieba_name = raw_input("请输入需要爬取的贴吧名:")

begin_page = raw_input("请输入爬取的起始页:")

end_page = raw_input("请输入爬取的结束页:")

Tieba = TiebaSpider(tieba_name, begin_page, end_page)

Tieba.start_work()

0c9b9ea383c72a812781ac0d222700c8.png

看完这个案例如果你对贴吧养号感兴趣的话还可以看下这个《贴吧养号需要换ip吗》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值