批量爬取百度贴吧里的标题及链接

基于数据加密的反爬:
自定义字体
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

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值