安装selenium并学习和学习IP相关知识

学习目标:

3.1 安装selenium并学习

  1. 安装selenium并学习。

  2. 使用selenium模拟登陆163邮箱。

  3. 163邮箱直通点:163网易免费邮-你的专业电子邮局 。

  4. 参考资料:Python爬虫学习-Day5-CSDN博客

3.2 学习IP相关知识

  1. 学习什么是IP,为什么会出现IP被封,如何应对IP被封的问题。

  2. 抓取西刺代理,并构建自己的代理池。

  3. 西刺直通点:https://www.xicidaili.com/ 。

  4. 参考资料:

  5. 爬虫学习Day6:ip-CSDN博客

  6. 爬虫学习日记3-构建免费代理池_爬虫构建代理池-CSDN博客

安装selenium

1、pip install selenium

2、cmd窗口下进入python,导入import selenium不报错说明安装成功

'''使用selenium模拟登陆163邮箱'''
from selenium import webdriver
import time
url = 'https://mail.163.com/'
driver = webdriver.Chrome()

driver.get(url=url)
time.sleep(10)
driver.switch_to.frame(0)#登陆框在第一个ifram,先切进去在执行其他事件
email = driver.find_element_by_name('email')
email.send_keys('xxxxxx')
password = driver.find_element_by_name('password')
password.send_keys('xxxxxxx')
time.sleep(2)
driver.find_element_by_id('dologin').click()
time.sleep(5)

IP为什么被封

网站为了防止被爬取,会有反爬机制,对于同一个IP地址的大量同类型的访问,会封锁IP,过一段时间后,才能继续访问

如何应对IP被封的问题

  1. 修改请求头,模拟浏览器(而不是代码去直接访问)去访问
  2. 采用代理IP并轮换
  3. 设置访问时间间隔

获取代理IP地址

import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
from threading import Thread
from datetime import datetime
start_time = datetime.now()

def get_xici_proxy(url,headers):
    response = requests.get(url, headers=headers).content
    res = response.decode('utf-8')
    soup = BeautifulSoup(res, 'lxml')
    tag_tr_all = soup.find_all('tr')
    # ['国家', 'IP地址', '端口', '服务器地址', '是否匿名', '类型', '速度', '连接时间', '存活时间', '验证时间']
    info_names = tag_tr_all[0].get_text().strip().split('\n')
    # global proxy_list
    t_list = []
    for tag_tr in tag_tr_all[1:]:    #从第1行开始遍历,应该遍历100次。
        tag_td = tag_tr.find_all('td')#
        try:
            country = tag_td[0].img['alt'] #td字标签img里的属性值,为国家缩写,但有的没有需处理异常
        except TypeError:#
            country = 'None'
        try:
            ip_info_list = [td.get_text(strip=True) for td in tag_td[1:]] #遍历1条代理的其它信息
            ip_info_list.insert(0,country)
            ip_info_dict = OrderedDict(zip(info_names,ip_info_list))
            t = Thread(target =check_proxy,args=(ip_info_dict,))
            t_list.append(t)
        except Exception as e:
            print("西陆站点登录错误:",e)
    for i in range(len(tag_tr_all[1:])):
        t_list[i].start()
    for i in range(len(tag_tr_all[1:])):
        t_list[i].join()

def check_proxy(info):
    # 居然要小写才行?今后抽空查资料看看是否这么一回事儿。
    proxy = {info['类型'].lower():r"{}://{}:{}".format(info['类型'].lower(),info['IP地址'],info['端口']),}
    try:
        response1 = requests.get(r"http://httpbin.org/get",proxies=proxy,timeout=10)
        print(response1.status_code)
        if response1.status_code==200:
            info['proxy'] = proxy
            proxy_list.append(info)
    except Exception as e:
        pass#
if __name__ == "__main__":
    url = r"https://www.xicidaili.com/nn"
    headers = {
        'User-Agent': "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"
    }
    proxy_list = [] #所有有效代理都存到一个list中
    get_xici_proxy(url,headers)

    print("有效代理数量:",len(proxy_list))
    print("第二个代理地址:",proxy_list[1].get('proxy'))
    print("第二个代理地址是否匿名:",proxy_list[1].get('是否匿名'))
    print("第二个代理地址类型:",proxy_list[1].get('类型'))
    print("检测的第二个代理地址存活时间:",proxy_list[1].get('存活时间'))
    print("_"*20)
    use_time = datetime.now()- start_time
    print("程序运行共计耗时:{}秒".format(use_time.seconds))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值