python自动投票源码(自动爬取更换ip)

import re
import random
import sys
import time
import datetime
import threading
from random import choice
import requests
import bs4
def get_ip():
    """获取代理IP"""
    url = "http://www.xicidaili.com/nn"
    headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
                "Accept-Encoding":"gzip, deflate, sdch",
                "Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6",
                "Referer":"http://www.xicidaili.com",
                "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
                }
    r = requests.get(url,headers=headers)
    soup = bs4.BeautifulSoup(r.text, 'html.parser')
    data = soup.table.find_all("td")
    ip_compile= re.compile(r'<td>(\d+\.\d+\.\d+\.\d+)</td>')    # 匹配IP
    port_compile = re.compile(r'<td>(\d+)</td>')                # 匹配端口
    ip = re.findall(ip_compile,str(data))       # 获取所有IP
    port = re.findall(port_compile,str(data))   # 获取所有端口
    return [":".join(i) for i in zip(ip,port)]  # 组合IP+端口,如:115.112.88.23:8080
# 设置 user-agent列表,每次请求时,可在此列表中随机挑选一个user-agnet
uas = [
    "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0; Baiduspider-ads) Gecko/17.0 Firefox/17.0",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9b4) Gecko/2008030317 Firefox/3.0b4",
    "Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; BIDUBrowser 7.6)",
    "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko",
    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0",
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36",
    "Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; Touch; LCJB; rv:11.0) like Gecko",
    ]
def get_url(code=0,ips=[]):
    """
        投票
        如果因为代理IP不可用造成投票失败,则会自动换一个代理IP后继续投
    """
    try:
        ip = choice(ips)
    except:
        return False
    else:
        proxies = {
            "http":ip,
        }
        headers2 = { "Accept":"text/html,application/xhtml+xml,application/xml;",
                        "Accept-Encoding":"gzip, deflate, sdch",
                        "Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6",
                        "Referer":"",
                        "User-Agent":choice(uas),
                        }
    try:
        num = random.uniform(0,1)
        hz_url = "http://www.xxxxx.com/xxxx%s" % num   # 某投票网站的地址,这里不用真实的域名
        hz_r = requests.get(hz_url,headers=headers2,proxies=proxies)
    except requests.exceptions.ConnectionError:
        print "ConnectionError"
        if not ips:
            print "not ip"
            sys.exit()
        # 删除不可用的代理IP
        if ip in ips:
            ips.remove(ip)
        # 重新请求URL
        get_url(code,ips)
    else:
        date = datetime.datetime.now().strftime('%H:%M:%S')
        print u"第%s次 [%s] [%s]:投票%s (剩余可用代理IP数:%s)" % (code,date,ip,hz_r.text,len(ips))
ips = []
for i in xrange(6000):
    # 每隔1000次重新获取一次最新的代理IP,每次可获取最新的100个代理IP
    if i % 1000 == 0:
        ips.extend(get_ip())
    # 启用线程,隔1秒产生一个线程,可控制时间加快投票速度 ,time.sleep的最小单位是毫秒
    t1 = threading.Thread(target=get_url,args=(i,ips))
    t1.start()
    time.sleep(1)


  • 7
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
使用Python实现自动登录网站并爬取数据的步骤: 1. 导入所需的库:requests、BeautifulSoup、selenium等。 2. 使用requests库模拟登录网站,获取登录后的cookies。 3. 使用selenium模拟浏览器操作,打开需要爬取的网页,并将cookies添加到浏览器。 4. 使用BeautifulSoup库解析网页HTML代码,提取需要的数据。 以下是一个示例代码,用于爬取某个网站的数据: ```python import requests from bs4 import BeautifulSoup from selenium import webdriver # 登录网站并获取cookies login_url = 'https://example.com/login' session = requests.Session() response = session.get(login_url) soup = BeautifulSoup(response.text, 'html.parser') csrf_token = soup.find('input', {'name': 'csrf_token'})['value'] login_data = { 'csrf_token': csrf_token, 'username': 'your_username', 'password': 'your_password' } session.post(login_url, data=login_data) # 使用selenium打开需要爬取的网页,并添加cookies browser = webdriver.Chrome('path/to/chromedriver') browser.get('https://example.com/data') cookies = session.cookies.get_dict() for key, value in cookies.items(): browser.add_cookie({'name': key, 'value': value}) # 解析网页HTML代码,提取数据 soup = BeautifulSoup(browser.page_source, 'html.parser') data = soup.find('div', {'class': 'data'}).text print(data) # 关闭浏览器 browser.quit() ``` 需要注意的是,以上代码仅作为示例,具体实现可能会因网站的特殊要求而有所不同。同时,不建议使用自动登录方式爬取需要登录才能访问的网站,除非你已获得网站的明确授权。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值