大家好,我是顺亿,今天和大家分享一个实用的Python爬虫技巧:如何爬取西刺代理的免费IP?这对于做爬虫的朋友来说,绝对是个加分项。
环境准备
我们这次使用的是Python 3.6和PyCharm,确保你的环境中已经安装了requests和BeautifulSoup这两个库。
核心代码解析
import requests
from bs4 import BeautifulSoup
import time
import random
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'}
def xici_ip(page):
for num_page in range(1, page + 1):
url_part = 'http://www.xicidaili.com/wn/'
url = url_part + str(num_page)
r = requests.get(url, headers=headers)
if r.status_code == 200:
soup = BeautifulSoup(r.text, 'lxml')
trs = soup.find_all('tr')
for i in range(1, len(trs)):
tr = trs[i]
tds = tr.find_all('td')
ip_item = tds[1].text + ':' + tds[2].text
with open(r'路径\get_xici_ip.txt', 'a', encoding='utf-8') as f:
f.writelines(ip_item + '\
')
return ('存储成功')
def get_ip():
with open(r'路径\get_xici_ip.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
return random.choice(lines)
def check_ip():
proxies = {'HTTPS': 'HTTPS://' + get_ip().replace('\
', '')}
try:
r = requests.get('http://httpbin.org/ip', headers=headers, proxies=proxies, timeout=10)
if r.status_code == 200:
return proxies
except Exception as e:
print(e)
def main():
xici_ip(1) # 抓取第一页,一页100个url
try:
return check_ip()
except Exception as e:
print(e)
check_ip()
if __name__ == '__main__':
main()
总结与拓展
以上就是爬取西刺代理免费IP的方法,简单又实用。如果你对爬虫技术感兴趣,可以关注我们「趣航编程网」(www.vqhf.com)了解更多相关内容。
顺亿
