Python爬虫编程实例(二):模拟丁香园登陆

  • 本文主要分为两个部分:ip代理的常见问题及解答和丁香园的模拟登陆
  • 学习交流请联系 [email protected]

ip代理答疑

Q1: 怎么在ip被封之后实现自动更换代理池内的代理?

A1: 用random.choice 随机选取ip

Q2: 如何用一句通俗的语言解释清楚request、beautifulsoup和selenium三者与浏览器之间的关系?

A2: BeautifulSoup:处理速度快,同时可以连续查找,主要用于静态网页

经过BeautifulSoup处理以后,编码方式都变成了Unicode,需要将其变成所需的编码方式:可以利用encode(‘需要的编码’),还可以利用 BeautifulSoup(网页/html, lxml/xml”).prettify(‘需要的编码’) 可以利用soup.original_encoding检测原来的编码。
Selenium:主要用于动态网页,查找速度慢,解析时要注意 .find_elementsby_xpath和.findelement_by_xpath有区别,同时利用浏览器时要配置。 .PhantomJS:
drive=webdriver.PhantomJS(‘D:\Anaconda2\phantomjswindows\binphantomjs.exe’)

Q3: 构建好代理池后,如何在一次爬虫中自动切换代理? 比如代理无效,或者代理ip被封,这时自动切换下一个ip。

A3: 首先你要有一个ip代理池(如果比较豪可以自己买真实ip自行搭建,好处独享有技术门槛,或者找第三方ip代理商对接,好处廉价,但ip不独享), 真实ip需要自己写程序来代理转发,第三方ip代理商则会提供相关转发API,直接调用就可以,这东西没什么技术难度

Q4: ip_list.append(f’{protpcol}: //{ip}:{port}’)这里的f是格式化?

A4:

  1. 从代理ip网站爬取IP地址及端口号并储存
  2. 验证ip是否能用
  3. 格式化ip地址
  4. requests中使用代理ip爬取网站

模拟丁香园登陆

URL:http://www.dxy.cn/bbs/thread/626626#626626

# 导入库
import requests, json, re, random,time
from bs4 import BeautifulSoup
from selenium import webdriver
from lxml import etree

# 定义类
class getUrl(object):
	"""docstring for getUrl"""
	def __init__(self):
		self.headers={
            "Connection": "keep-alive",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "  
                          "(KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate, sdch",
            "Accept-Language": "zh-CN,zh;q=0.8"
        };

	def run(self):
		browser = webdriver.Chrome("C:/Users/SHOHOKU/Desktop/Python/chromedriver")
		browser.get('https://auth.dxy.cn/accounts/login?service=http://www.dxy.cn/bbs/index.html')
		time.sleep(1)
		#切换账号密码登录表单
		js1 = 'document.querySelector("#j_loginTab1").style.display="none";'
		browser.execute_script(js1)
		time.sleep(1)
		js2 = 'document.querySelector("#j_loginTab2").style.display="block";'
		browser.execute_script(js2)
		#输入账号密码
		input_name = browser.find_element_by_name('April_0911')
		input_name.clear()
		input_name.send_keys('123456..')
		input_pass = browser.find_element_by_name('password')
		input_pass.clear()
		input_pass.send_keys('*')
		browser.find_element_by_xpath('//*[@class="form__button"]/button').click()
		#此步骤应该有验证码,先跳过
		time.sleep(10)
		cookie = browser.get_cookies()
		cookie_dict = {i['name']:i['value'] for i in cookie}
		#转到抓取页面
		browser.get("http://www.dxy.cn/bbs/thread/626626#626626");
		html = browser.page_source
		tree = etree.HTML(html)
		user = tree.xpath('//div[@id="postcontainer"]//div[@class="auth"]/a/text()')
		content = tree.xpath('//td[@class="postbody"]')
		for i in range(0,len(user)):
			result = user[i].strip()+":"+content[i].xpath('string(.)').strip()
			#写入文件
			dir_file = open("DXY_records.txt",'a', encoding="utf-8")
			dir_file.write(result+"\n")
			dir_file.write('*' * 80+"\n")
			dir_file.close()
		print('*' * 5 +"抓取结束"+'*' * 5)


if __name__ == '__main__':
	geturl = getUrl()
	geturl.run()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章