Python爬虫怎么使用代理IP?

作者:IPIDEA

2022-09-26 11:55:53

  你可能会觉得爬虫有些复杂,经常IP被网站封了,还得去找ip代理商获取ip才可以继续爬虫。这是因为网站会保护自己的服务器和信息。

Python爬虫怎么使用代理IP?.png

  Python爬虫应该经历爬虫、爬虫和爬虫的允许访问公开数据过程。当然,网页爬虫允许访问公开数据优化和爬虫反允许访问公开数据的一系列过程。爬虫的初级阶段,添加headers和ip代理可以解决很多问题。

  下面我们跟着IPIDEA,来看看Python抓取ip具体代码操作:

  运行环境:

  Python 3.7, Pycharm

  这些都需要大家直接建立环境...

  准备工作:

  爬取IP网站地址(国内高匿代理)

  爬取IP完整代码:

  PS:简单的使用bs4获取IP和端口号没什么难度,里面加了一个不可用的过滤器。IP的逻辑,以下关键地方都有注释了。

  #!/usr/bin/env python3

  # -*- coding: utf-8 -*-

  # @Time : 2018/11/22

  # @Author : liangk

  # @Site :

  # @File : auto_archive_ios.py

  # @Software: PyCharm

  import requests

  from bs4 import BeautifulSoup

  import json

  class GetIp(object):

  """抓取ip代理"""

  def __init__(self):

  """初始化变量"""

  self.url = http://www.xicidaili.com/nn/

  self.check_url = https://www.ip.cn/

  self.ip_list = []

  @staticmethod

  def get_html(url):

  """请求html页面信息"""

  header = {

  User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36 }

  try:

  request = requests.get(url=url, headers=header)

  request.encoding = utf-8

  html = request.text

  return html

  except Exception as e:

  return

  def get_available_ip(self, ip_address, ip_port):

  """检测IP地址是否可用"""

  header = {

  User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36 }

  ip_url_next = :// ip_address : ip_port

  proxies = {http: http ip_url_next, https: https ip_url_next}

  try:

  r = requests.get(self.check_url, headers=header, proxies=proxies, timeout=3)

  html = r.text

  except:

  print(fail-%s % ip_address)

  else:

  print(success-%s % ip_address)

  soup = BeautifulSoup(html, lxml)

  div = soup.find(class_=well)

  if div:

  print(div.text)

  ip_info = {address: ip_address, port: ip_port}

  self.ip_list.append(ip_info)

  def main(self):

  """主方法"""

  web_html = self.get_html(self.url)

  soup = BeautifulSoup(web_html, lxml)

  ip_list = soup.find(id=ip_list).find_all(tr)

  for ip_info in ip_list:

  td_list = ip_info.find_all(td)

  if len(td_list) > 0:

  ip_address = td_list[1].text

  ip_port = td_list[2].text

  # 检测IP地址是否有效

  self.get_available_ip(ip_address, ip_port)

  # 写有效文件

  with open(ip.txt, w) as file:

  json.dump(self.ip_list, file)

  print(self.ip_list)

  # 程序主入口

  if __name__ == __main__:

  get_ip = GetIp()

  get_ip.main()

  当然,这些只是用ip代理爬虫的日常操作,爬虫大神可能对这些并不感到惊讶。如果你需要选择便宜的爬虫ip代理,欢迎咨询IPIDEA。


*ipidea提供的服务必须在境外网络环境下使用

热门资讯