【爬虫】Python使用requests爬取代理IP并验证可用性

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/okm6666/article/details/79484784

在编写爬虫的过程中为了避免IP地址被Ban掉,可以通过抓取IP代理后,通过代理IP进行对网页的访问。网络上有很多提供免费代理IP的网站,我们可以选择西刺进行代理IP的爬取并存储到csv文件中,并通过多进程来验证爬取IP的可用性。

http://www.xicidaili.com/就提供了很多免费的代理IP。

通过requests和lxml进行网页的爬取和解析。
在爬取之前我们首先设置请求头,模拟作为普通浏览器进行网页的访问。

headers = {
    'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    'accept-encoding': "gzip, deflate",
    'accept-language': "zh-CN,zh;q=0.9",
    'cache-control': "no-cache",
    'connection': "keep-alive",
    'host': "www.xicidaili.com",
    'if-none-match': "W/\"61f3e567b1a5028acee7804fa878a5ba\"",
    'upgrade-insecure-requests': "1",
    'user-agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36"
}

关于headers的设置可以同过POSTMAN自动生成代码。
要爬取的页面结构非常简单,通过lxml的css选择器选择所有的ip地址和端口进行拼接,然后一行行的写入到csv文件中。
代码如下:

def getProxyList(target_url=TARGET_URL, pages='1'):
    """
    爬取代理IP地址
    :param target_url: 爬取的代理IP网址
    :return:
    """
    proxyFile = open(FILE_NAME, "a+", newline="")
    writer = csv.writer(proxyFile)

    r = requests.get(target_url + pages, headers=headers, timeout=2.5)
    document_tree = lxml.html.fromstring(r.text)
    rows = document_tree.cssselect("#ip_list tr")
    rows.pop(0)
    for row in rows:
        tds = row.cssselect("td")
        proxy_ip = tds[1].text_content()
        proxy_port = tds[2].text_content()
        proxy_addr = tds[3].text_content().strip()
        writer.writerow([proxy_ip, proxy_port, proxy_addr])

    proxyFile.close()

自己设置好爬取的页面走个循环,爬取好的地址就写入到了csv文件中。不过之前发布的一些代理IP不能用的可能性较大,可以就爬取前5页左右即可。

在验证代理IP的可行性时,通过进程池添加验证每个代理IP的验证方法即可。通过requests的session可以持续的进行网络的访问。

def verifyProxies(verify_url, file_path=FILE_NAME):
    session = requests.session()
    proxyFile = open(FILE_NAME, "r+")
    csv_reader = csv.reader(proxyFile)
    p = Pool(10)
    for row in csv_reader:
        proxies = {"http": "http://" + row[0] + ":" + row[1]}
        p.apply_async(verifyProxy, args=(verify_url, proxies, session))
    p.close()
    p.join()
    proxyFile.close()

验证每个IP的方法就是通过给网页发送GET请求,然后根据返回的状态码进行判断,并执行相应的操作。在请求时设置了timeout的话,需要使用try-except抛出异常,否则当超过timeout设置的值时,会终止相应的进程。

猜你喜欢

转载自blog.csdn.net/okm6666/article/details/79484784