基于数据加密的反爬:
自定义字体
css偏移
js生成
图片
编码格式
代码
可以发现,我们需要的数据在源码中被注释掉了,所以我们需要处理一下。
import re
import requests
from lxml import etree
# 指定url
url='https://tieba.baidu.com/f?ie=utf-8&kw=python'
# 参数
# 请求头
header = {
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
'Access-Control-Allow-Credentials': 'true',
'Connection': 'keep-alive',
'Accept-Language': 'zh-CN,zh;q=0.9',
# 'Referer':'https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%B0%8F%E7%A7%98'
}
data_= [] # 存储信息
count=0 # 计数
pro={
'http':'http://47.104.15.198:80'
}
while url!=None:
count += 1
r=requests.get(url,headers=header,proxies=pro)
r_text=r.text.replace('-->','').replace('<!--','') #解决被注释掉的问题
tree=etree.HTML(r_text)
data_list=tree.xpath('//li[@class=" j_thread_list clearfix thread_item_box"]/div/div[2]/div[1]/div[1]/a')
for data in data_list:
data_dic={}
title=data.xpath('./text()')[0]
link='https://tieba.baidu.com/'+ data.xpath('./@href')[0]
data_dic[title]=link
data_.append(data_dic)
try:
url='https:'+tree.xpath('//a[contains(text(),"下一页")]/@href')[0]
except:
url=None
for i in data_:
print(i)
print(count) #爬取的页面数
print(len(data_)) #爬取的信息数
运行结果
但这里有一个问题,(请求链接次数,频率过高,导致封IP)
每次运行返回结果之后都会有冷却,被拉黑。。。再运行就不会返回给结果,过一段时间才能继续运行此代码。
解决问题----->设置代理池
# 可以检测目前使用的 IP
https://www.httpbin.org/ip
# 设置代理池
url='申请的代理IP对应的API链接'
r_text=requests.get(url).text
tree=etree.HTML(r_text)
proxy_list=tree.xpath('//body//text()')
proxy_pool=[] #代理池
for proxy in proxy_list:
dic={
'http':proxy
}
proxy_pool.append(dic)
# 代理池设置完毕
requests.get(url_new,headers,proxies=random.choice(proxy_pool)) # 随机选用一个代理 IP