代理池IP爬取
網(wǎng)絡(luò)上提供免費(fèi)代理的網(wǎng)站:
以上述兩家代理為例。一般網(wǎng)站的代理數(shù)據(jù)均以表格樣式展現(xiàn)。如下圖

表格類的數(shù)據(jù)
總體代碼
- 爬取
- 解析
- 驗(yàn)證
- 存儲
爬取
封裝文件讀寫操作
-
使用requests爬取網(wǎng)頁,使用緩存
- 緩存是將網(wǎng)頁存儲在
temp文件夾中,按照一定規(guī)則命名。按時(shí)檢查。 - 不能直接使用hash來進(jìn)行文件的區(qū)分[1]
# 增加文件緩存 if not os.path.isfile(path): print('writing file') content = requests.get(url=url, headers={'user-agent': 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.3; Win64; x64)'}).text crower_table.write_file_content(path, content) return content else: return crower_table.get_file_content(path) - 緩存是將網(wǎng)頁存儲在
解析
table這邊只考慮了兩種情況。一種是table標(biāo)簽下只有tr標(biāo)簽, 第二種是標(biāo)準(zhǔn)格式。
- 取出tr標(biāo)簽,第一個(gè)tr標(biāo)簽作為標(biāo)題
- 清除掉文字中的特殊字符
- 輸出標(biāo)準(zhǔn)格式的json字符串
def get_table_content(table):
“”“
這里主要是對類似于
<tr></tr>
<tr></tr>
...
這類數(shù)據(jù)進(jìn)行處理,第一行定義表格數(shù)據(jù)的屬性,存在titles中,其余行保存數(shù)據(jù)內(nèi)容。
”“”
if table.find('thead') is None:
trs = table.find_all('tr')
first_tr = trs[0]
others_tr = trs[1:]
titles = [th.get_text() for th in first_tr.find_all('th')]
results = []
for one_other in others_tr:
temp = [t.get_text().replace('\n', '') for t in one_other.find_all('td')]
per = {titles[k]: temp[k] for k in range(0, len(titles) - 1)}
results.append(per)
return results
正確將各種不同類別的表格類數(shù)據(jù)進(jìn)行格式化是一個(gè)相對復(fù)雜的工作。這里只是對其中的一種情況進(jìn)行處理。
驗(yàn)證
- 通過代理訪問baidu,判斷返回頁面的狀態(tài)碼是否是200
- 將結(jié)果存入輸出
def validate_ip(ip, protocol):
test_url = 'http://baidu.com'
try:
proxy_host = {protocol: protocol + "://" + ip}
html = requests.get(test_url, proxies=proxy_host, timeout=3, headers={'user-agent': 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.3; Win64; x64)'})
if html.status_code == 200:
print('success',proxy_host)
return True
else:
print('Failed', proxy_host)
return False
except Exception:
return 'error'
存儲
在python3與mysql的直接交互推薦使用pymysql。當(dāng)然也可以使用ORM類工具
- 安裝python3-devel 和 mysql-devel
- 使用pymysql進(jìn)行安裝
- 安裝
cryptograph
插入數(shù)據(jù)庫的基本操作
進(jìn)階考慮
- 如何進(jìn)行代理的及時(shí)更新
- 利用多個(gè)代理ip同時(shí)從不同斷點(diǎn)下載大文件
素材
-
原來的想法是通過命名存儲的臨時(shí)文件為
hash(url),但是python3中會增加一個(gè)seed,只能保證運(yùn)行時(shí)hash值不會更新。 ?