本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。
前文内容💨Python爬虫入门教程01:豆瓣Top电影爬取
Python爬虫入门教程02:小说爬取
Python爬虫入门教程03:二手房数据爬取
Python爬虫入门教程04:招聘信息爬取
Python爬虫入门教程05:B站视频弹幕的爬取
Python爬虫入门教程06:爬取数据后的词云图制作
Python爬虫入门教程07:腾讯视频弹幕爬取
Python爬虫入门教程08:爬取csdn文章保存成PDF
Python爬虫入门教程09:多线程爬取表情包图片
Python爬虫入门教程10:彼岸壁纸爬取
Python爬虫入门教程11:新版王者荣耀皮肤图片的爬取
Python爬虫入门教程12:英雄联盟皮肤图片的爬取
Python爬虫入门教程13:高质量电脑桌面壁纸爬取
Python爬虫入门教程14:有声书音频爬取
Python爬虫入门教程15:音乐网站数据的爬取
Python爬虫入门教程17:音乐歌曲的爬取
Python爬虫入门教程18:好看视频的爬取
Python爬取入门教程19:YY短视频的爬取
PS:如有需要 Python学习资料
以及 解答
的小伙伴可以加点击下方链接自行获取 python免费学习资料以及群交流解答点击即可加入
- Python 3.6
- Pycharm
import requests # 第三方模块
import parsel
import time # 时间模块
安装Python并添加到环境变量,pip安装需要的相关模块即可。
一、💥确定目标需求 获取代理IP地址,端口然后对IP进行检测
网站是静态网页,是可以直接获取数据的。 根据re、xpath或者css选择器 都是可以提取数据的,还是比较简单的。爬取IP主要是因为在使用爬虫频繁抓取数据的时候,某些网站是比较容易被封IP的。
虽然网站有很多关于免费的IP代理可以使用,但是基本上都是用不了的。
完整代码import requests # 第三方模块
import parsel
import time # 时间模块
def check_ip(proxies_list):
"""检测代理ip的可用性"""
use_proxy = []
for ip in proxies_list:
try:
response = requests.get(url='https://www.baidu.com', proxies=ip, timeout=2)
if response.status_code == 200:
use_proxy.append(ip)
except Exception as e:
print('当前代理ip: ', ip, '请求超时, 检测不合格!!!')
else:
print('当前代理ip: ', ip, '检测通过')
return use_proxy
proxy_list = []
for page in range(1, 11):
time.sleep(0.5)
print(f'==================正在抓取第{page}页数据================')
# 1.确定数据所在地址(分析网页性质)
url = f'http://www.ip3366.net/?stype=1&page={page}'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'}
# 2.发送网络请求
response = requests.get(url=url, headers=headers)
html_data = response.text # str
# print(html_data)
# 3.解析数据
# 3.1 转换数据类型
selector = parsel.Selector(html_data)
# 3.2 数据提取
trs = selector.xpath('//table[@class="table table-bordered table-striped"]/tbody/tr') # tr
"""
# 代理ip的结构
proxies_dict = {
"http": "http://" + ip:端口,
"https": "http://" + ip:端口,
}
"""
for tr in trs:
ip_num = tr.xpath('./td[1]/text()').get()
ip_port = tr.xpath('./td[2]/text()').get()
# print(ip_num, ip_port)
ip_proxy = ip_num + ':' + ip_port
# print(ip_proxy)
proxies_dict = {
'http': "http://" + ip_proxy,
'https': "https://" + ip_proxy
}
# 4.数据的保存
proxy_list.append(proxies_dict)
print('保存成功:', proxies_dict)
print(proxy_list)
print('获取到的代理ip数量: ', len(proxy_list))
print('============================正在检测代理===================================')
can_use = check_ip(proxy_list)
print('可用代理:', can_use)
print('可用代理数量:', len(can_use))
爬取了100IP代理,最终可以使用的就只有一个,事实证明还是付费的香