import requests
import parsel
page_num = 1
for page in range(0,57000+1,50):
print("==============正在爬取第{}页=========".format(page_num))
page_num+=1
# 1.分析目标网页,确定爬取到url路径, headers参数
base_url = "https://tieba.baidu.com/f?kw=%E7%BA%A6%E4%BC%9A&ie=utf-8&pn={}".format(page)
headers = {
'User-Agent': "User-Agent:Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0"
}
# 2.发送请求,requests,模拟浏览器发送请求,获取相应数据
# 这是一个对象,利用.text来提取其中的数据
response = requests.get(url=base_url, headers=headers)
html_str = response.text
# print(html_str)
# 3.解析数据 parsel 转化为Selector对象,Selector对象具有xpath的方法,能够对转化的数据进行处理
html = parsel.Selector(html_str)
# 这里使用谷歌的请求头一直请求不出内容,换了IE的请求头即可。
title_url = html.xpath('//div[@class="threadlist_title pull_left j_th_tit "]/a/@href').extract()
for title in title_url:
all_url = "https://tieba.baidu.com" + title
response_2 = requests.get(url=all_url, headers=headers).text
response_2_data = parsel.Selector(response_2)
pic_url = response_2_data.xpath(
'//div[@class="d_post_content j_d_post_content "]/img[@class="BDE_Image"]/@src').extract()
for pic in pic_url:
file_name = pic.split('/')[-1]
img = requests.get(url=pic, headers=headers).content
# 4.数据保存
with open('img\\' + file_name, "wb") as f:
f.write(img)
网友评论