python爬虫類はどのように自分の代理IPプールを創立します
17731 ワード
独自のエージェントIPプールを構築し、Webサイトのデータをキャプチャするためにいつでも更新します.
fake_useragent使用例
独自のIPエージェントプールの構築
有料のオープンエージェントを取得するインタフェースを書く
3、有料オープンエージェントIPを使用してテストサイトにアクセスする:http://httpbin.org/getプライベートエージェント 構文フォーマット
サンプルコード
fake_useragent使用例
# 1 User-Agent
from fake_useragent import UserAgent
ua = UserAgent()
print(ua.random)
独自のIPエージェントプールの構築
import requests
import random
from lxml import etree
from fake_useragent import UserAgent
# User-Agent
def get_random_ua():
# User-Agent
ua = UserAgent()
# 1 User-Agent
return ua.random
# IP : http://httpbin.org/get
url = 'http://httpbin.org/get'
# IP
def get_ip_list():
headers = {'User-Agent': get_random_ua()}
# , tr
res = requests.get('https://www.xicidaili.com/nn/', headers=headers)
parse_html = etree.HTML(res.text)
# xpath, IP
ipobj_list = parse_html.xpath('//tr')
# , IP
ip_list = []
# 2 , 1 : ( 、IP、... ...)
for ip in ipobj_list[1:]:
ip_info = ip.xpath('./td[2]/text()')[0]
port_info = ip.xpath('./td[3]/text()')[0]
ip_list.append(
{
'http': 'http://' + ip_info + ':' + port_info,
'https': 'https://' + ip_info + ':' + port_info
}
)
# IP ( ip_list)
return ip_list
#
def main_print():
# IP
ip_list = get_ip_list()
#
for proxy_ip in ip_list:
try:
# ,
headers = {'User-Agent': get_random_ua()}
res = requests.get(url=url, headers=headers, proxies=proxy_ip, timeout=5)
res.encoding = 'utf-8'
print(res.text)
except Exception as e:
# IP ,
ip_list.remove(proxy_ip)
print('%s , ' % proxy_ip)
# 1 IP
continue
#
with open('proxies.txt','a') as f:
for ip in ip_list:
f.write(ip + '
')
if __name__ == '__main__':
main_print()
有料のオープンエージェントを取得するインタフェースを書く
# getip.py
#
import requests
# IP
def get_ip_list():
api_url = 'http://dev.kdlapi.com/api/getproxy/?orderid=996140620552954&num=100&protocol=2&method=2&an_an=1&an_ha=1&sep=1'
res = requests.get(api_url)
ip_port_list = res.text.split('\r
')
return ip_port_list
if __name__ == '__main__':
proxy_ip_list = get_ip_list()
print(proxy_ip_list)
3、有料オープンエージェントIPを使用してテストサイトにアクセスする:http://httpbin.org/get
1、 api
2、 api IP
3、 IP
from getip import *
import time
import random
url = 'http://httpbin.org/get'
headers = {'User-Agent' : 'Mozilla/5.0'}
proxy_ip_list = get_ip_list()
while True:
#
if not proxy_ip_list:
proxy_ip_list = get_ip_list()
proxy_ip = random.choice(proxy_ip_list)
proxies = {
'http' : 'http://{}'.format(proxy_ip),
'https' : 'https://{}'.format(proxy_ip)
}
print(proxies)
try:
html = requests.get(url=url,proxies=proxies,headers=headers,timeout=5,verify=False).text
print(html)
break
except:
print(' IP, ... ...')
# IP
proxy_ip_list.remove(proxy_ip)
continue
1、
proxies = {
' ':' :// : @IP: '
}
2、
proxies = {
'http':'http:// : @IP: ',
'https':'https:// : @IP: '
}
サンプルコード
import requests
url = 'http://httpbin.org/get'
proxies = {
'http': 'http://309435365:[email protected]:16819',
'https':'https://309435365:[email protected]:16819',
}
headers = {
'User-Agent' : 'Mozilla/5.0',
}
html = requests.get(url,proxies=proxies,headers=headers,timeout=5).text
print(html)