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()

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