python爬蟲由淺入深(非scrapy版)

流程:requests— xpath、css定位(文本)—定位并下載(非文本)— 動(dòng)態(tài)加載(selenium)—post網(wǎng)站—selenium爬取post
準(zhǔn)備工作
  • 安裝python,推薦直接安裝anoconda或者miniconda,不用折騰
  • 編輯器推薦VS code,輕便且功能強(qiáng)大,不推薦sublime(配置較麻煩),較不推薦pycharm(代碼提示能力很強(qiáng),但是有種看用ps看圖片的感覺,不適合日常使用)
  • 下載chromedriver,并置于系統(tǒng)環(huán)境
1.最常用的requests
優(yōu)先考慮requests爬取
import requests
url='http://car.bitauto.com/aodia3-3999/peizhi/'
head=dict() # 設(shè)置agent
head['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'  # 添加代理,有些網(wǎng)站回識(shí)別requests,加瀏覽器代理,百利無害
rq=requests.get(url=url,headers=head)  # 爬取
rq.encoding="utf-8"  # 或者用rq.content.decode('utf-8'),需要看網(wǎng)頁是用什么編碼寫的,亂碼了考慮utf-8換成gbk
print(rq.text)
# VScode輸出中文亂碼推薦看(http://www.itdecent.cn/p/e634bff989f2)
f = open("spider.txt","w",encoding="utf-8")
f.write(rq.text) # 爬取的東西寫到文本里
f.close() # 記得關(guān)閉
2.網(wǎng)頁內(nèi)容定位(文本)
xpath定位或者css定位,不推薦beautifulsoup(較麻煩且較前者無顯著優(yōu)勢)
# 注意該代碼塊緊跟上一個(gè)代碼塊
import lxml.html as path
tree = path.fromstring(rq.text) # 編譯
# htl = path.tostring(tree) # 編譯回string
tdcss=tree.cssselect('body > header > div.middle-nav-box > div > div.brand-info > h1 > a:nth-child(2)')[0].text_content()  # css定位
tdxpath=tree.xpath('/html/body/header/div[2]/div/div[1]/h1/a[2]')[0].text_content() # xpath定位
# 文本處理
print(tdxpath[-2:]) # 直接取倒數(shù)第二及之后
print(tdxpath.replace("奧迪","")) # replace函數(shù)
print(tdxpath.split("迪")[1]) # split切片
import re
print("".join(re.findall('[A-Z0-9]',tdxpath))) # findall函數(shù)非常重要,可以自己學(xué)習(xí)
2.網(wǎng)頁內(nèi)容定位并下載(非文本)
# 注意該代碼塊緊跟上一個(gè)代碼塊
# 下載圖片
td=tree.xpath('/html/body/header/div[2]/div/div[1]/h1/a[1]/img/@src')[0] # 用@取屬性
url1='http:'+td # 構(gòu)造完整url
img = requests.get(url=url1).content # 圖片內(nèi)容
with open('a.jpg','wb') as f:
    f.write(img) # 下載圖片,用with open()就不需要f.close()
3.不能直接定位(動(dòng)態(tài)加載)
# 注意該代碼塊緊跟上一個(gè)代碼塊
td=tree.xpath('//*[@id="tr2,2,2_0,1,2"]/td[1]')
print(td) # 無法定位詳細(xì)數(shù)據(jù),動(dòng)態(tài)加載,解析或者考慮Selenium
4.selenium爬?。▌?dòng)態(tài)加載)
一般通過js或xhr實(shí)現(xiàn)動(dòng)態(tài)加載,有興趣的可以解析后用requests,沒興趣或者很難解析的直接用selenium
from selenium import webdriver

f = open("spider.txt","w",encoding="utf-8")
opt=webdriver.ChromeOptions()
opt.add_argument('-headless') # 無界面
prefs = {"profile.managed_default_content_settings.images":2}  # 無圖加載,更快
opt.add_experimental_option("prefs",prefs)
driver=webdriver.Chrome(chrome_options=opt) # 作者將chromedriver.exe放在系統(tǒng)環(huán)境下了
url='http://car.bitauto.com/aodia3-3999/peizhi/'
driver.get(url)
t=len(driver.find_elements_by_xpath('//*[@id="tr2,2,2_0,1,2"]/td')) # 計(jì)算有多少個(gè)td標(biāo)簽
for num in range(1,(t+1)):
    A0=driver.find_element_by_xpath('//*[@id="draggcarbox_%s"]/dl/dd[1]/a' % str(num-1)).text
    A1=driver.find_element_by_xpath('//*[@id="tr2,2,2_0,1,2"]/td[%s]' % str(num)).text # %s代表一個(gè)字符串,str表示轉(zhuǎn)換成字符串,text表示取文字部分
    # print(driver.find_element_by_xpath('//*[@id="CarCompareContent"]/table/tbody/tr[20]/td[%s]' % str(num)).text)
    # print(driver.find_element_by_xpath('//*[@id="tr2,2,2_0,1,2"]/following-sibling::tr[1]/td[%s]'% str(num)).text) # 以id為準(zhǔn),變一個(gè),翻頁爬蟲時(shí)更加穩(wěn)定
    A2=driver.find_element_by_xpath("http://*[text()='軸距[mm]']/following-sibling::td[%s]" % str(num)).text  # 以文字為準(zhǔn),變一個(gè),翻頁爬蟲時(shí)更加穩(wěn)定,following-sibling表示下兄弟節(jié)點(diǎn)
    print(A0+'\t'+A1+'\t'+A2)  # 、t表示制表符tab,\n表示分行
    f.write(A0+'\t'+A1+'\t'+A2+'\n') # 只寫入第一頁
    f.close() # 記得關(guān)
driver.quit()
5.post網(wǎng)頁爬取
post網(wǎng)站,網(wǎng)頁內(nèi)容變化但是網(wǎng)址不變
import requests

f = open("spider.txt", "w", encoding="utf-8")
url = 'http://www.chinanpo.gov.cn/search/orgcx.html'
header={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
    'Referer':'http://www.chinanpo.gov.cn/search/orgcx.html'
} #request headers部分,Cookie有時(shí)候是必要的,這里沒加上
## 注意requests.get也可以用上述字典,比只加agent效果可能會(huì)更好?。。。?!
formdata = dict(tabIndex=2,
               t=2,
               orgName=r'%E5%8C%BB%E9%99%A2', # 醫(yī)院的網(wǎng)頁解碼
               regDate='2014-12-01',
               regDateEnd='2018-07-28') # formdata部分
a = requests.post(url,data=formdata,headers=header)
f.write(a.text)
a.close()  # 關(guān)閉訪問,養(yǎng)成好習(xí)慣?
6.selenium爬取post網(wǎng)站
有些post網(wǎng)頁中會(huì)有動(dòng)態(tài)加載,不想解析的話可以用selenium一并解決
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common import keys

f = open("spider.txt", "w", encoding="utf-8")
opt=webdriver.ChromeOptions()
opt.add_argument('-headless')  # 無界面
driver = webdriver.Chrome(chrome_options=opt)
url='http://kns.cnki.net/kns/brief/default_result.aspx'
driver.implicitly_wait(4)  # 隱性等待,最多等4秒來加載
driver.get(url)
s = Select(driver.find_element_by_css_selector('#txt_1_sel'))
s.select_by_visible_text('篇名')  # 選擇篇名
# driver.maximize_window() # 最大化窗口
driver.find_element_by_xpath('//*[@id="txt_1_value1"]').send_keys('urbanization economic')  # 輸入關(guān)鍵詞
driver.find_element_by_xpath('//*[@id="txt_1_value1"]').send_keys(keys.Keys.RETURN)  # 回車
# 后續(xù)可以根據(jù)需要繼續(xù)driver爬取
print(driver.find_element_by_xpath('//*[@id="SCDB"]/a').text) # 用.text來取文本部分
print(driver.find_element_by_xpath('//*[@id="HeaderDiv"]/div[1]/div[2]/a/img[1]').get_attribute("src")) # 用.get_attribute來獲取屬性
附(for myself):pdf處理比較麻煩,pdf可以用pdfminer包來轉(zhuǎn)文本,但是建議用adobe acrobat來直接轉(zhuǎn),后者轉(zhuǎn)換能力更強(qiáng)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過簡信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容