sess = requests.Session() #返回一个session对象
#第一次调用session一定是为了捕获cookie
main_url = ‘https://xueqiu.com/‘
sess.get(main_url,headers=headers) #目的:尝试捕获cookie,cookie就会被存储到session
url = ‘https://xueqiu.com/statuses/hot/listV2.json?since_id=-1&max_id=65993&size=15‘
#已经表示携带cookie发起了请求
json_data = sess.get(url=url,headers=headers).json()
json_data
from lxml import etree
#没有使用代理获取的本机ip
url = ‘https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=ip‘
page_text = requests.get(url=url,headers=headers).text
tree = etree.HTML(page_text)
#在xpath表达式中不可以出现tbody标签,否则会解析出错
ip_data = tree.xpath(‘//*[@id="1"]/div[1]/div[1]/div[2]/table//tr/td/span/text()‘)
ip_data
[‘本机IP:\xa0106.115.33.66‘]
#使用代理
url = ‘https://www.sogou.com/web?query=ip&_asf=www.sogou.com&_ast=&w=01019900&p=40040100&ie=utf8&from=index-nologin&s_from=index&sut=731&sst0=1592443705688&lkt=2%2C1592443704957%2C1592443705064&sugsuv=00A3ECEE7B7013775D31BAFA55B79106&sugtime=1592443705688‘
#proxies参数:请求设置代理
page_text = requests.get(url=url,headers=headers,proxies={‘https‘:‘27.40.92.66:36542‘}).text
# tree = etree.HTML(page_text)
# #在xpath表达式中不可以出现tbody标签,否则会解析出错
# ip_data = tree.xpath(‘//*[@id="1"]/div[1]/div[1]/div[2]/table//tr/td/span/text()‘)
# ip_data
with open(‘./ip.html‘,‘w‘,encoding=‘utf-8‘) as fp:
    fp.write(page_text)
代理池构建
#尝试发起高频请求,让对方服务器将本机ip禁掉
url = ‘https://www.xicidaili.com/nn/%d‘
ips = []
for page in range(1,30):
    new_url = format(url%page)
    page_text = requests.get(new_url,headers=headers).text
    tree = etree.HTML(page_text)
    #不要第一个tr
    tr_list = tree.xpath(‘//*[@id="ip_list"]//tr‘)[1:]
    for tr in tr_list:
        ip = tr.xpath(‘./td[2]/text()‘)[0]
        ips.append(ip)
print(len(ips))
#发现本机ip被禁掉
proxy_list = [] #代理池
proxy_url = ‘http://t.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&groupid=0&qty=20&time=1&pro=&city=&port=1&format=html&ss=5&css=&dt=1&specialTxt=3&specialJson=&usertype=2‘
page_text = requests.get(url=proxy_url,headers=headers).text
tree = etree.HTML(page_text)
ips_list = tree.xpath(‘//body//text()‘)
for ip in ips_list:
    dic = {‘https‘:ip}
    proxy_list.append(dic)
    
url = ‘https://www.xicidaili.com/nn/%d‘
ips = []
for page in range(1,5):
    new_url = format(url%page)
    page_text = requests.get(new_url,headers=headers,proxies=random.choice(proxy_list)).text
    tree = etree.HTML(page_text)
    #不要第一个tr
    tr_list = tree.xpath(‘//*[@id="ip_list"]//tr‘)[1:]
    for tr in tr_list:
        ip = tr.xpath(‘./td[2]/text()‘)[0]
        ips.append(ip)
print(len(ips))
url = ‘https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx‘
page_text = requests.get(url,headers=headers).text
tree = etree.HTML(page_text)
img_src = ‘https://so.gushiwen.org‘+tree.xpath(‘//*[@id="imgCode"]/@src‘)[0]
img_data = requests.get(url=img_src,headers=headers).content
with open(‘./code.jpg‘,‘wb‘) as fp:
    fp.write(img_data)
#!/usr/bin/env python
# coding:utf-8
import requests
from hashlib import md5
class Chaojiying_Client(object):
    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode(‘utf8‘)
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            ‘user‘: self.username,
            ‘pass2‘: self.password,
            ‘softid‘: self.soft_id,
        }
        self.headers = {
            ‘Connection‘: ‘Keep-Alive‘,
            ‘User-Agent‘: ‘Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)‘,
        }
    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            ‘codetype‘: codetype,
        }
        params.update(self.base_params)
        files = {‘userfile‘: (‘ccc.jpg‘, im)}
        r = requests.post(‘http://upload.chaojiying.net/Upload/Processing.php‘, data=params, files=files, headers=self.headers)
        return r.json()
    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            ‘id‘: im_id,
        }
        params.update(self.base_params)
        r = requests.post(‘http://upload.chaojiying.net/Upload/ReportError.php‘, data=params, headers=self.headers)
        return r.json()
def transform_codeImg(imgPath,imgType):
    chaojiying = Chaojiying_Client(‘bobo328410948‘, ‘bobo328410948‘, ‘899370‘)	#用户中心>>软件ID 生成一个替换 96001
    im = open(imgPath, ‘rb‘).read()			#本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    return chaojiying.PostPic(im, imgType)[‘pic_str‘]		#1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()
transform_codeImg(‘./code.jpg‘,1004)
‘e9gj‘
session = requests.Session()
url = ‘https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx‘
page_text = session.get(url,headers=headers).text
tree = etree.HTML(page_text)
img_src = ‘https://so.gushiwen.org‘+tree.xpath(‘//*[@id="imgCode"]/@src‘)[0]
img_data = session.get(url=img_src,headers=headers).content
__VIEWSTATE = tree.xpath(‘//*[@id="__VIEWSTATE"]/@value‘)[0]
__VIEWSTATEGENERATOR = tree.xpath(‘//*[@id="__VIEWSTATEGENERATOR"]/@value‘)[0]
with open(‘./code.jpg‘,‘wb‘) as fp:
    fp.write(img_data)
code_text = transform_codeImg(‘./code.jpg‘,1004)#验证码内容
print(code_text)
login_url = ‘https://so.gushiwen.org/user/login.aspx?from=http%3a%2f%2fso.gushiwen.org%2fuser%2fcollect.aspx‘
data = {
    ‘__VIEWSTATE‘: __VIEWSTATE,
    ‘__VIEWSTATEGENERATOR‘: __VIEWSTATEGENERATOR,
    ‘from‘: ‘http://so.gushiwen.org/user/collect.aspx‘,
    ‘email‘: ‘15027900535‘,
    ‘pwd‘: ‘bobo@328410948‘,
    ‘code‘: code_text,
    ‘denglu‘: ‘登录‘,
}
page_text = session.post(url=login_url,headers=headers,data=data).text
with open(‘./login.html‘,‘w‘,encoding=‘utf-8‘) as fp:
    fp.write(page_text)
原文:https://www.cnblogs.com/freedom0923/p/13167635.html