日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

利用python爬虫(案例5)--X刺代理的小IP们

發(fā)布時間:2023/12/19 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 利用python爬虫(案例5)--X刺代理的小IP们 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

學(xué)習(xí)筆記


爬取X刺代理的小IP們

學(xué)完代理,我們發(fā)現(xiàn)網(wǎng)上找的很多免費代理IP都用不了,所以這里寫一個簡單的測試小案例,爬取一下某代理IP網(wǎng)站的免費代理IP,再遍歷測試到底這些代理IP能不能用,哪些能用。


爬取步驟

獲取要爬取的代理IP網(wǎng)站地址(http://www.xicidaili.com/nn/)

爬取頁面內(nèi)所有的代理IP及其端口號

測試代理IP

將可以用的代理IP存在一個csv文件里。


因為這個案例不是很復(fù)雜,所以我們就不寫怎么查看網(wǎng)頁源代碼,怎么寫Xpath,怎么研究URL特征這些步驟了,直接上代碼


python代碼

為了節(jié)省時間,我只測試了19個代理IP:

# -*- coding: utf-8 -*-import requests from lxml import etree from fake_useragent import UserAgent import time import csvclass IpSpider:def __init__(self):self.url = 'http://www.xicidaili.com/nn/'def get_ua(self):return UserAgent().randomdef get_page(self):headers = {'User-Agent':self.get_ua()}res = requests.get(self.url, headers = headers)html = res.content.decode('utf-8')print('url:', res.url)print('code:', res.status_code)#print(html)self.get_ip_list(html)def get_ip_list(self, html):html_parse = etree.HTML(html)xpath = '//table[@id="ip_list"]//tr'r_list = html_parse.xpath(xpath)#print(r_list)proxy_list = []for p in r_list[1:20]:my_ip = p.xpath('./td[2]/text()')[0]my_port = p.xpath('./td[3]/text()')[0]#print('代理IP:', my_ip)proxy_list.append({'http':'http://{}:{}'.format(my_ip, my_port), 'https':'https://{}:{}'.format(my_ip, my_port)})self.test_ip(proxy_list)def test_ip(self, proxy_list):useful_proxy = []for proxy in proxy_list:print(proxy)headers = {'User-Agent':self.get_ua()}try:res = requests.get(self.url, headers = headers,proxies = proxy,timeout = 4)#如果請求超過3秒沒有相應(yīng)則默認(rèn)該代理不能用except Exception as e:print('此代理IP無法使用......')else:useful_proxy.append(proxy)print(proxy)self.write_ip(useful_proxy)def write_ip(self, proxy_list):with open('./test/my_test_proxy.csv', 'w', newline = '') as f:writer = csv.writer(f)writer.writerow(['http', 'https'])for item in proxy_list:writer.writerow([item['http'], item['https']])def main(self):self.get_page()if __name__ == '__main__':start = time.time()spider = IpSpider()spider.main()end = time.time()print('執(zhí)行時間:%.2f' % (end-start))

部分結(jié)果:

此代理IP無法使用...... {'http': 'http://111.231.239.143:1081', 'https': 'https://111.231.239.143:1081'} 此代理IP無法使用...... {'http': 'http://115.223.64.38:8010', 'https': 'https://115.223.64.38:8010'} 此代理IP無法使用...... 執(zhí)行時間:70.16

可用的代理IP


我們打開存放可用代理IP的csv文件,看一下有哪些IP:

http,https http://125.126.117.30:60004,https://125.126.117.30:60004 http://125.126.113.184:60004,https://125.126.113.184:60004 http://112.16.217.191:808,https://112.16.217.191:808

好了,這個小案例完結(jié)…

總結(jié)

以上是生活随笔為你收集整理的利用python爬虫(案例5)--X刺代理的小IP们的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。