開發環境
- Python 3.8
- Pycharm
模塊使用
- requests >>> pip install requests
- parsel >>> pip install parsel
代理ip結構
proxies_dict = { "http": "http://" + ip:埠, "https": "http://" + ip:埠, }
對于本篇文章有疑問的同學可以加【資料白嫖、解答交流群:910981974】
代碼實作步驟:
1. 匯入模塊
# 匯入資料請求模塊 import requests # 資料請求模塊 第三方模塊 pip install requests # 匯入 正則運算式模塊 import re # 內置模塊 # 匯入資料決議模塊 import parsel # 資料決議模塊 第三方模塊 pip install parsel >>> 這個是scrapy框架核心組件
2. 發送請求, 對于目標網址發送請求 https://www.kuaidaili.com/free/
url = f'https://www.kuaidaili.com/free/inha/{page}/' # 確定請求url地址 # 用requests模塊里面get 方法 對于url地址發送請求, 最后用response變數接識訓傳資料 response = requests.get(url)
3. 獲取資料, 獲取服務器回傳回應資料(網頁源代碼)
print(response.text)
4. 決議資料, 提取我們想要的資料內容
決議資料方式方法:
- 正則: 可以直接提取字串資料內容
- xpath: 根據標簽節點 提取資料內容
- css選擇器: 根據標簽屬性提取資料內容
哪一種方面用那種, 那是喜歡用那種
正則運算式提取資料內容
正則提取資料 re.findall() 呼叫模塊里面的方法
正則 遇事不決 .*? 可以匹配任意字符(除了換行符\n以外) re.S
ip_list = re.findall('<td data-title="IP">(.*?)</td>', response.text, re.S) port_list = re.findall('<td data-title="PORT">(.*?)</td>', response.text, re.S) print(ip_list) print(port_list)
css選擇器:
css選擇器提取資料 需要把獲取下來html字串資料(response.text) 進行轉換
# #list > table > tbody > tr > td:nth-child(1) # //*[@id="list"]/table/tbody/tr/td[1] selector = parsel.Selector(response.text) # 把html 字串資料轉成 selector 物件 ip_list = selector.css('#list tbody tr td:nth-child(1)::text').getall() port_list = selector.css('#list tbody tr td:nth-child(2)::text').getall() print(ip_list) print(port_list)
xpath 提取資料
selector = parsel.Selector(response.text) # 把html 字串資料轉成 selector 物件 ip_list = selector.xpath('//*[@id="list"]/table/tbody/tr/td[1]/text()').getall() port_list = selector.xpath('//*[@id="list"]/table/tbody/tr/td[2]/text()').getall()
提取ip
for ip, port in zip(ip_list, port_list): # print(ip, port) proxy = ip + ':' + port proxies_dict = { "http": "http://" + proxy, "https": "http://" + proxy, } print(proxies_dict)

5. 檢測ip質量
try: response = requests.get(url=url, proxies=proxies_dict, timeout=1) if response.status_code == 200: print('當前代理IP: ', proxies_dict, '可以使用') lis_1.append(proxies_dict) except: print('當前代理IP: ', proxies_dict, '請求超時, 檢測不合格') print('獲取的代理IP數量: ', len(lis)) print('獲取可用的IP代理數量: ', len(lis_1)) print('獲取可用的IP代理: ', lis_1)

總共爬取了150個,最后測驗出只有一個是能用的,所以還是付費的好
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419023.html
標籤:其他
上一篇:初始Python系列
