文章目录
User-Agent是一个特殊字符串头,被广泛用来标示浏览器客户端的信息,使得服务器能识别客户机使用的操作系统和版本,CPU类型,浏览器及版本,浏览器的渲染引擎,浏览器语言等。
1. 安装fake_useragent:
pip install fake_useragent
2. 导入fake_useragent
from fake_useragent import UserAgent
3. fake_useragent的获取
headers = {'User-Agent':str(UserAgent().random)}
'''
'''
4. User-Agent的使用
req = requests.get(url=url, headers=headers)
'''
(二)代理ip的使用,一般都是使用的api模式的,程序获取ip然后自己建ip池进行管理,可以控制ip的使用,大部分都是这样使用的。我最近改变了使用方式,使用的是动态转发模式的,真的不要太方便好用。大家可以试试,举例一个框架的使用示例
JSoup
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import org.jsoup.Jsoup
;import org.jsoup.nodes.Document;
public class Demo{
// 代理隧道验证信息
final static String ProxyUser = "16KASDA";
final static String ProxyPass = "1231321";
// 代理服务器
final static String ProxyHost = "t.16yun.cn";
final static Integer ProxyPort = 31111;
// 设置IP切换头
final static String ProxyHeadKey = "Proxy-Tunnel";
public static String getUrlProxyContent(String url)
{
Authenticator.setDefault(new Authenticator() {
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(ProxyUser, ProxyPass.toCharArray());
}
});
// 设置Proxy-Tunnel
Random random = new Random();
int tunnel = random.nextInt(10000);
String ProxyHeadVal = String.valueOf(tunnel);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ProxyHost, ProxyPort));
try
{
// 处理异常、其他参数
Document doc = Jsoup.connect(url).timeout(3000).header(ProxyHeadKey, ProxyHeadVal).proxy(proxy).get();
if(doc != null) {
System.out.println(doc.body().html());
}
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception
{
// 要访问的目标页面
String targetUrl = "http://httpbin.org/ip";
getUrlProxyContent(targetUrl);
}}
(三)
try:
proxies = get_random_ip(ip_list)
headers = {'User-Agent':str(UserAgent().random)}
req = requests.get(url=url, proxies=proxies,headers=headers,timeout=20)
except:
time.sleep(5)
proxies = get_random_ip(ip_list)
headers = {'User-Agent':str(UserAgent().random)}
req = requests.get(url=url, proxies=proxies,headers=headers,timeout=20)
'''
timeout=20:当请求超过20秒还没得到服务器的相应时中断请求
'''