python爬虫隐藏自身的ip并伪装成浏览器

摘自:https://blog.csdn.net/jasonLee_lijiaqi/article/details/79384777

爬虫隐藏自身的ip并伪装成浏览器

1、使用代理访问

就是说使用代理Ip,代理ip访问url之后,再将网页的内容在传给本机的ip;

'''
使用代理访问
'''
import urllib.request
import random

url = 'http://www.whatismyip.com.tw'

#创建一个iplist,随机使用ip
iplist = ['219.223.251.173:3128','203.174.112.13:3128','122.72.18.34:80']
#创建一个代理opener
proxy_support = urllib.request.ProxyHandler({'http':iplist[random.randint(0, len(iplist))]})
opener = urllib.request.build_opener(proxy_support)

#添加浏览器的伪装头部
opener.addheaders = [('User-Agent','Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0')]

#使用代理opener访问url
response = opener.open(url)


html = response.read().decode('utf-8')
print(html)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

2、伪装成浏览器

隐藏————伪装成浏览器 
两种方法: 
1、通过Request的headers参数修改 
2、通过Request.add_header()方法修改 
在User-Agent中替换成浏览器的User-Agent

'''
import urllib.request

url = r'http://douban.com'
headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0'}

#urllib.request.Request()用于向服务端发送请求,就如 http 协议客户端向服务端发送请求 POST
#添加了一个头部,伪装成浏览器,此时的url并不是一个裸露的url,而是具有header头部的url
req = urllib.request.Request(url=url, headers=headers)

#urllib.request.urlopen()则相当于服务器返回的响应,返回的是一个request类的一个对象, GET
# 类似于一个文件对象,可以进行open()操作获取内容
res = urllib.request.urlopen(req)

html = res.read().decode('utf-8')
print(html)

猜你喜欢

转载自blog.csdn.net/qq_38712932/article/details/80426181
今日推荐