使用Python抓取网页时欺骗 IP 地址
在本文中,我们将通过在Python中轮换代理来使用 Requests 废弃一个网站。
所需模块
- 要求 模块允许您发送 HTTP 请求并返回包含所有数据(例如状态、页面内容等)的响应。
句法:
requests.get(url, parameter)
- JSON JavaScript Object Notation是一种用于结构化数据的格式。它主要用于在浏览器和服务器之间存储和传输数据。 Python也通过一个名为 json 的内置包支持 JSON。这个包提供了处理 JSON 对象的所有必要工具,包括解析、序列化、反序列化等等。
方法
- 如果您没有使用rapidapi,请手动创建一组http 代理。 (这里使用create_proxy()函数使用rapidapi生成一组http代理)
- 迭代代理集并使用requests.get(url, proxies=proxies)将GET请求连同代理作为参数发送到网站。
句法:
requests.get(url, proxies=proxies)
- 如果代理工作正常,那么它应该返回一个 URL 对象。
除了使用代码之外,还有一些设置需要完成,下面给出了这些设置的详细信息。
使用 Rapidapi 获取一组代理:
- 首先,您需要从rapidapi购买该API的订阅,然后转到仪表板并选择Python并复制api_key。
- 使用 API 密钥和 Rapidapi 主机初始化标头。
句法:
headers = {
‘x-rapidapi-key’: “paste_api_key_here”,
‘x-rapidapi-host’: “proxy-orbit1.p.rapidapi.com”
}
- 向 API 发送 GET 请求以及标头,
句法:
response = requests.request(“GET”, url, headers=headers)
- 这将返回一个 JSON,使用 json.loads() 解析文本,我们可以在“curl”键中找到代理服务器地址。
句法:
response = json.loads(response.text)
proxy = response[‘curl’]
在 requests.get() 中发送代理作为参数:
使用requests.get()和一个代理发送一个GET请求到这个 url,它将返回当前会话的代理服务器地址。
句法:
# Note : Opening https://ipecho.net/plain in browser will show the current ip address of the session.
proxies = ‘http://78.47.16.54:80’
page = requests.get(‘https://ipecho.net/plain’, proxies={“http”: proxy, “https”: proxy})
print(page.text)
程序:
Python3
import requests
import json
# Gets proxies from rapidapi to create
# a set of proxies.
# Use this function only if you have rapidapi key.
def create_proxy():
url = "https://proxy-orbit1.p.rapidapi.com/v1/"
# Initialise the headers and paste the API key
# of proxy-orbit1 from rapidapi.
headers = {
'x-rapidapi-key': "paste_api_key_here",
'x-rapidapi-host': "proxy-orbit1.p.rapidapi.com"
}
# Sends a GET request to the above url along with api
# keys which returns an object containing data in json
# format which is then parsed using json.loads.
response = requests.request("GET", url, headers=headers)
response = json.loads(response.text)
# The proxy server ip address is present in 'curl' key.
proxy = response['curl']
return proxy
# Main Function
if __name__ == "__main__":
# Create an empty set and call the create_proxy()
# function to generate a set of proxies from rapidapi.
# Orbit proxy Rapid api key is required.
proxies = set()
print("Creating Proxy List")
for __ in range(10):
proxies.add(create_proxy())
# If you do not have rapidapi then create a set of
# proxies manually.
# proxies = {'http://78.47.16.54:80',
# 'http://203.75.190.21:80', 'http://77.72.3.163:80'}
# Iterate the proxies and check if it is working.
for proxy in proxies:
print("\nChecking proxy:", proxy)
try:
# https://ipecho.net/plain returns the ip address
# of the current session if a GET request is sent.
page = requests.get('https://ipecho.net/plain',
proxies={"http": proxy, "https": proxy})
print("Status OK, Output:", page.text)
except OSError as e:
# Proxy returns Connection error
print(e)
输出: