Requests :唯一的一個非轉(zhuǎn)基因的 Python HTTP 庫,人類可以安全享用。
直接調(diào)用requests.get
import requests
response = requests.get('https://www.baidu.com')
import requests
params = {'wd': 'python'}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4090.0 Safari/537.36 Edg/83.0.467.0'}
# params: 接受一個字典或者字符串的查詢參數(shù),字典類型自動轉(zhuǎn)換為url編碼,不需要urlencode()
response = requests.get('https://www.baidu.com', params=params, headers=headers)
# 查看響應內(nèi)容,response.text返回的是Unicode格式的數(shù)據(jù)
print(response.text)
# 查看響應內(nèi)容,response.content返回的是字節(jié)流數(shù)據(jù)
print(response.content.decode('utf-8'))
# 查看完整url地址
print(response.url)
# 查看響應頭部字符編碼
print(response.encoding)
# 查看響應碼
print(response.status_code)
直接調(diào)用requests.post,如果返回的是json數(shù)據(jù),可以調(diào)用response.json()來將json字符串轉(zhuǎn)為字典或列表
下面是爬取拉勾網(wǎng)的一個示例,記得請求頭添加Cookie,才能成功爬取到
import requests
data = {'first': 'true',
'pn': '1',
'kd': 'python'}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/83.0.4090.0 Safari/537.36 Edg/83.0.467.0',
'Referer': 'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=',
'Cookie': 'user_trace_token=20200331183800-0c1f510a-ae9a-4f04-b70d-e17f9edec031; '
'LGUID=20200331183800-b8eca414-b7b2-479d-8100-71fff41d8087; _ga=GA1.2.17010052.1585651081; '
'index_location_city=%E5%85%A8%E5%9B%BD; lagou_utm_source=B; _gid=GA1.2.807051168.1585805257; '
'sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22171302b7caa67e-0dedc0121b2532-255e0c45'
'-2073600-171302b7cabb9c%22%2C%22%24device_id%22%3A%22171302b7caa67e-0dedc0121b2532-255e0c45'
'-2073600-171302b7cabb9c%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B'
'%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_referrer%22%3A%22%22%2C%22'
'%24latest_referrer_host%22%3A%22%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5'
'%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%7D%7D; '
'JSESSIONID=ABAAABAABFIAAAC7D7CECCAFCFFA1FCBF3CB10D8EA6A189; '
'WEBTJ-ID=20200403095906-1713dc35e58a75-0b564b9cba1732-23580c45-2073600-1713dc35e598e; PRE_UTM=; '
'PRE_HOST=; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F; '
'LGSID=20200403095905-8201da05-4bb8-4e93-97bf-724ea6f758af; '
'PRE_SITE=https%3A%2F%2Fwww.lagou.com; _gat=1; '
'Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1585651082,1585879146; TG-TRACK-CODE=index_search; '
'X_HTTP_TOKEN=0b356dc3463713117419785851e40fa7a09468f3f0; '
'Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1585879149; '
'LGRID=20200403095908-4f1711b9-3e7e-4d54-a400-20c76b57f327; '
'SEARCH_ID=b875e8b91a764d63a2dc98d822ca1f85'}
response = requests.post('https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false',
headers=headers,
data=data)
print(response.json())
這里在基礎中已經(jīng)講到過,使用requests只需要兩行代碼,非常方便
import requests
proxy = {'http': '59.44.78.30:54069'}
response = requests.get('http://httpbin.org/ip', proxies=proxy)
print(response.text)
使用session在多次請求中共享cookie,可以發(fā)現(xiàn)相比使用urllib代碼變得特別簡潔
import requests
headers = {'User-Agent': ''}
data = {'email': '',
'password': ''}
login_url = 'http://www.renren.com/PLogin.do'
profile_url = 'http://www.renren.com/880151247/profile'
session = requests.Session()
session.post(login_url, data=data, headers=headers)
response = session.get(profile_url)
with open('renren.html', 'w', encoding='utf-8') as f:
f.write(response.text)
對于那些沒有被信任的SSL證書的網(wǎng)站,可以在requests.get和requests.post中設置參數(shù)verify=False來進行訪問
xpath(XML Path Language)是一門在XML和HTML文檔中查找信息的語言,可用來在XML和HTML文檔中對元素和屬性進行訪問。
XPath使用路徑表達式來選取XML文檔中的節(jié)點或者節(jié)點集,這些路徑表達式和我們在常規(guī)的電腦文件系統(tǒng)中的表示式非常類似。
表達式 | 描述 | 示例 | 結(jié)果 |
nodename | 選取此節(jié)點的所有子節(jié)點 | bookstore | 選取bookstore下所有的子節(jié)點 |
/ | 如果在最前面,代表從根節(jié)點選取,否則選擇某節(jié)點下的某個節(jié)點 | /bookstore | 選取根元素下所有的bookstore節(jié)點 |
// | 從全局節(jié)點中選擇節(jié)點,隨便在哪個位置 | //book | 從全局節(jié)點中找到所有的book節(jié)點 |
@ | 選取某個節(jié)點的屬性 | //book[@price] | 選擇所有擁有price屬性的book節(jié)點 |
謂語用來查找某個特定的節(jié)點或者包含某個指定節(jié)點的值的節(jié)點,被嵌在方括號中。
路徑表達式 | 描述 |
/bookstore/book[1] | 選取bookstore下的第一個book元素 |
/booksotre/book[last()] | 選取bookstore下的最后一個book元素 |
/bookstore/book[position()??] | 選取bookstore下前面兩個book元素 |
//book[@price] | 選擇所有擁有price屬性的book節(jié)點 |
//book[@price=10] | 選取所有屬性price=10的book元素 |
通配符 | 描述 | 示例 | 結(jié)果 |
* | 匹配任意節(jié)點 | /bookstore/* | 選取bookstore下的所有子元素 |
@* | 匹配節(jié)點中的任何屬性 | //book[@*] | 選取所有帶有屬性的book元素 |
通過在路徑表達式中使用|運算符,可以選取若干個路徑
//bookstore/book | //book/title
# 選取多個book元素以及book元素下的title元素
運算符 | 描述 | 實例 | 返回值 |
| | 計算兩個節(jié)點集 | //book | //cd | 返回所有擁有book和cd元素的節(jié)點集 |
+,-,*,div | 加,減,乘,除 | 6+1, 6-1, 6 * 1, 6 div 1 | 7, 5, 6, 6 |
=, !=, <, <=, >, >= | - | - | 返回false或true |
or, and | 或,與 | - | 返回false或true |
mod | 計算除法的余數(shù) | 5 mod 2 | 1 |
//div[contains(@class, 'job_detail')]
3.謂詞中的下標從1開始。
lxml是一個HTML/XML的解析器,主要功能是如何解析和提取HTML/XML數(shù)據(jù)。
1,解析html字符串:使用lxml.etree.HTML進行解析
from lxml import etree
htmlElement = etree.HTML(text)
print(etree.tostring(htmlElement, encoding='utf-8').decode('utf-8'))
2,解析html文件:使用lxml.etree.parse進行解析
htmlElement = etree.parse('tencent.xml')
print(etree.tostring(htmlElement, encoding='utf-8').decode('utf-8'))
這個函數(shù)默認使用XML解析器,所以如果碰到不規(guī)范的HTML代碼的時候就會解析錯誤,這時候要創(chuàng)建HTML解析器
parser = etree.HTMLParser(encoding='utf-8')
htmlElement = etree.parse('tencent.xml', parser=parser)
print(etree.tostring(htmlElement, encoding='utf-8').decode('utf-8'))
from lxml import etree
parser = etree.HTMLParser(encoding='utf-8')
html = etree.parse('tencent.html', parser=parser)
trs = html.xpath('//tr')
for tr in trs:
print(etree.tostring(tr, encoding='utf-8').decode('utf-8'))
tr = html.xpath('//tr[2]')[0]
print(etree.tostring(tr, encoding='utf-8').decode('utf-8'))
trs = html.xpath("//tr[@class='even']")
for tr in trs:
print(etree.tostring(tr, encoding='utf-8').decode('utf-8'))
aList = html.xpath('//a/@href')
for a in aList:
print('http://hr.tencent.com/' + a)
注我——個人公眾號:后端技術(shù)漫談
我目前是一名后端開發(fā)工程師。主要關(guān)注后端開發(fā),數(shù)據(jù)安全,網(wǎng)絡爬蟲,物聯(lián)網(wǎng),邊緣計算等方向。
原創(chuàng)博客主要內(nèi)容
image
最近做了一個python3作業(yè)題目,涉及到:
涉及到的庫有:
放出代碼方便大家快速參考,實現(xiàn)一個小demo。
搜索引擎的設計與實現(xiàn)
["http://fiba.qq.com/a/20190420/001968.htm", "http://sports.qq.com/a/20190424/000181.htm", "http://sports.qq.com/a/20190423/007933.htm", "http://new.qq.com/omn/SPO2019042400075107"]
1 "http:xxxxxx.htm" 3 2 "https:xxxx.htm" 2 3 "https:xxxxx.htm" 1
代碼實現(xiàn)的主要步驟是:
import requests from bs4 import BeautifulSoup import json import re import jieba import time USER_AGENT = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) ' 'Chrome/20.0.1092.0 Safari/536.6'} URL_TIMEOUT = 10 SLEEP_TIME = 2 # dict_result格式:{"1": # {"url": "xxxxx", "word": {"word1": x, "word2": x, "word3": x}} # "2": # {"url": "xxxxx", "word": {"word1": x, "word2": x, "word3": x}} # } dict_result = {} # dict_search格式:[ # [url, count] # [url, count] # ] list_search_result = [] def crawler(list_URL): for i, url in enumerate(list_URL): print("網(wǎng)頁爬取:", url, "...") page = requests.get(url, headers=USER_AGENT, timeout=URL_TIMEOUT) page.encoding = page.apparent_encoding # 防止編碼解析錯誤 result_clean_page = bs4_page_clean(page) result_chinese = re_chinese(result_clean_page) # print("網(wǎng)頁中文內(nèi)容:", result_chinese) dict_result[i + 1] = {"url": url, "word": jieba_create_index(result_chinese)} print("爬蟲休眠中...") time.sleep(SLEEP_TIME) def bs4_page_clean(page): print("正則表達式:清除網(wǎng)頁標簽等無關(guān)信息...") soup = BeautifulSoup(page.text, "html.parser") [script.extract() for script in soup.findAll('script')] [style.extract() for style in soup.findAll('style')] reg1 = re.compile("<[^>]*>") content = reg1.sub('', soup.prettify()) return str(content) def re_chinese(content): print("正則表達式:提取中文...") pattern = re.compile(u'[\u1100-\uFFFD]+?') result = pattern.findall(content) return ''.join(result) def jieba_create_index(string): list_word = jieba.lcut_for_search(string) dict_word_temp = {} for word in list_word: if word in dict_word_temp: dict_word_temp[word] += 1 else: dict_word_temp[word] = 1 return dict_word_temp def search(string): for k, v in dict_result.items(): if string in v["word"]: list_search_result.append([v["url"], v["word"][string]]) # 使用詞頻對列表進行排序 list_search_result.sort(key=lambda x: x[1], reverse=True) if __name__ == "__main__": list_URL_sport = input("請輸入網(wǎng)址列表:") list_URL_sport = list_URL_sport.split(",") print(list_URL_sport) # 刪除輸入的網(wǎng)頁雙引號 for i in range(len(list_URL_sport)): list_URL_sport[i] = list_URL_sport[i][1:-1] print(list_URL_sport) # list_URL_sport = ["http://fiba.qq.com/a/20190420/001968.htm", # "http://sports.qq.com/a/20190424/000181.htm", # "http://sports.qq.com/a/20190423/007933.htm", # "http://new.qq.com/omn/SPO2019042400075107"] time_start_crawler = time.time() crawler(list_URL_sport) time_end_crawler = time.time() print("網(wǎng)頁爬取和分析時間:", time_end_crawler - time_start_crawler) word = input("請輸入查詢的關(guān)鍵詞:") time_start_search = time.time() search(word) time_end_search = time.time() print("檢索時間:", time_end_search - time_start_search) for i, row in enumerate(list_search_result): print(i+1, row[0], row[1]) print("詞頻信息:") print(json.dumps(dict_result, ensure_ascii=False))
image
我目前是一名后端開發(fā)工程師。主要關(guān)注后端開發(fā),數(shù)據(jù)安全,網(wǎng)絡爬蟲,物聯(lián)網(wǎng),邊緣計算等方向。
微信:yangzd1102
Github:@qqxx6661
個人博客:
原創(chuàng)博客主要內(nèi)容
個人公眾號:后端技術(shù)漫談
如果文章對你有幫助,不妨收藏起來并轉(zhuǎn)發(fā)給您的朋友們~
從事前端開發(fā)過程中,瀏覽器作為最重要的開發(fā)環(huán)境,瀏覽器基礎是是前端開發(fā)人員必須掌握的基礎知識點,它貫穿著前端的整個網(wǎng)絡體系。對瀏覽器原理的了解,決定著編寫前端代碼性能的上限。瀏覽器作為JS的運行環(huán)境,學習總結(jié)下現(xiàn)代瀏覽器的相關(guān)知識
前言
經(jīng)常聽說瀏覽器內(nèi)核,瀏覽器內(nèi)核究竟是什么,以及它做了什么。我們將來了解下瀏覽器的主要組成部分、現(xiàn)代瀏覽器的主要架構(gòu)、瀏覽器內(nèi)核、瀏覽器內(nèi)部是如何工作的
1 瀏覽器
現(xiàn)代瀏覽器結(jié)構(gòu)如下:
The browser's main component
The User Interface
主要提供用戶與Browser Engine交互的方法。其中包括:地址欄(address bar)、向前/退后按鈕、書簽菜單等等。瀏覽器除了渲染請求頁面的窗口外的所有地方都屬于The User Interface
The Browser Engine
協(xié)調(diào)(主控)UI和the Rendering Engine,在他們之間傳輸指令。 提供對The Rendering Engine的高級接口,一方面它提供初始化加載Url和其他高級的瀏覽器動作(如刷新、向前、退后等)方法。另一方面Browser Engine也為User Interface提供各種與錯誤、加載進度相關(guān)的消息。
The Rendering Engine
為給定的URL提供可視化的展示。它解析JavaScript、Html、Xml,并且User Interface中展示的layout。其中關(guān)鍵的組件是Html解析器,它可以讓Rendering Engine展示差亂的Html頁面。 值得注意:不同的瀏覽器使用不同的Rendering Engine。例如IE使用Trident,F(xiàn)irefox使用Gecko,Safai使用Webkit。Chrome和Opera使用Webkit(以前是Blink)
The Networking
基于互聯(lián)網(wǎng)HTTP和FTP協(xié)議,處理網(wǎng)絡請求。網(wǎng)絡模塊負責Internet communication and security,character set translations and MIME type resolution。另外網(wǎng)絡模塊還提供獲得到文檔的緩存,以減少網(wǎng)絡傳輸。為所有平臺提供底層網(wǎng)絡實現(xiàn),其提供的接口與平臺無關(guān)
The JavaScript Interpreter
解釋和運行網(wǎng)站上的js代碼,得到的結(jié)果傳輸?shù)絉endering Engine來展示。
The UI Backend
用于繪制基本的窗口小部件,比如組合框和窗口。而在底層使用操作系統(tǒng)的用戶界面方法,并公開與平臺無關(guān)的接口。
The Data Storage
管理用戶數(shù)據(jù),例如書簽、cookie和偏好設置等。
2 主流瀏覽器的架構(gòu)
2.1 FireFox
FireFox的架構(gòu)
可以看到火狐瀏覽器的渲染引擎(Rendering Engine)使用的是Gecko;XML Parser解析器是Expat;Java Script解釋器是Spider-Monkey(c語言實現(xiàn))
2.2 Chrome
Chrome的架構(gòu)
渲染引擎Rendering Engine使用的是WebKit
XML Parser: libXML解析XML,libXSLT處理XSLT
JS解釋器使用C++實現(xiàn)的V8引擎,
2.3 IE
IE的架構(gòu)
渲染引擎主要是Trident
Scripting Engine有JScript和VBScript
3 瀏覽器內(nèi)核
瀏覽器最重要或者說核心的部分是“Rendering Engine”,可大概譯為“渲染引擎”,不過我們一般習慣將之稱為“瀏覽器內(nèi)核”。主要包括以下線程:
3.1 瀏覽器 GUI 渲染線程,主要包括:
? HTML Parser 解析HTML文檔,將元素轉(zhuǎn)換為樹結(jié)構(gòu)DOM節(jié)點,稱之為Content Tree
? CSS Parser 解析Style數(shù)據(jù),包括外部的CSS文件以及在HTML元素中的樣式,用于創(chuàng)建另一棵樹,調(diào)用“Render Tree”
? Layout過程 為每個節(jié)點計算出在屏幕中展示的準確坐標
? Painting 遍歷Render Tree,調(diào)用UI Backend提供的接口繪制每個節(jié)點
3.2 JavaScript 引擎線程
JS引擎線程負責解析Javascript腳本,運行代碼 JS引擎一直等待著任務隊列中任務的到來,然后加以處理,一個Tab頁(renderer進程)中無論什么時候都只有一個JS線程在運行JS程序
GUI渲染線程與JS引擎線程是互斥的,所以如果JS執(zhí)行的時間過長,這樣就會造成頁面的渲染不連貫,導致頁面渲染加載阻塞
a) 減少 JavaScript 加載對 DOM 渲染的影響(將 JavaScript 代碼的加載邏輯放在 HTML 文件的尾部,減少對渲染引擎呈現(xiàn)工作的影響; b) 避免重排,減少重繪(避免白屏,或者交互過程中的卡頓; c) 減少 DOM 的層級(可以減少渲染引擎工作過程中的計算量; d) 使用 requestAnimationFrame 來實現(xiàn)視覺變化(一般來說我們會使用 setTimeout 或 setInterval 來執(zhí)行動畫之類的視覺變化,但這種做法的問題是,回調(diào)將在幀中的某個時點運行,可能剛好在末尾,而這可能經(jīng)常會使我們丟失幀,導致卡頓)
3.3 瀏覽器定時觸發(fā)器線程
瀏覽器定時計數(shù)器并不是由 JavaScript 引擎計數(shù)的, 因為 JavaScript 引擎是單線程的, 如果處于阻塞線程狀態(tài)就會影響記計時的準確, 因此通過單獨線程來計時并觸發(fā)定時是更為合理的方案
3.4 瀏覽器事件觸發(fā)線程
當一個事件被觸發(fā)時該線程會把事件添加到待處理隊列的隊尾,等待 JavaScript 引擎的處理。這些事件可以是當前執(zhí)行的代碼塊如定時任務、也可來自瀏覽器內(nèi)核的其他線程如鼠標點擊、AJAX 異步請求等,但由于 JavaScript 的單線程關(guān)系所有這些事件都得排隊等待 JavaScript 引擎處理。
3.5 瀏覽器 http 異步請求線程
在 XMLHttpRequest 在連接后是通過瀏覽器新開一個線程請求, 將檢測到狀態(tài)變更時,如果設置有回調(diào)函數(shù),異步線程就產(chǎn)生狀態(tài)變更事件放到 JavaScript 引擎的處理隊列中等待處理。
4 以Chrome瀏覽器為例,演示瀏覽器內(nèi)部如何工作
上面鋪墊了這么多理論,下面結(jié)合Chrome講解當用戶在地址欄上輸入URL后,瀏覽器內(nèi)部都做了寫什么
4.1 Chrome瀏覽器中的多進程
打開Chrome 任務管理器,可以看到
Chrome運行的進程
各個進程的功能
? Browser進程
功能:Controls "chrome" part of the application including address bar, bookmarks, back and forward buttons. Also handles the invisible, privileged parts of a web browser such as network requests and file access.
? GPU進程
功能:Handles GPU tasks in isolation from other processes. It is separated into different process because GPUs handles requests from multiple apps and draw them in the same surface.
? 第三方插件進程
功能:Controls any plugins used by the website, for example, flash. 每個插件對應一個進程,當插件運行時創(chuàng)建
? 瀏覽器渲染進程
功能:Controls anything inside of the tab where a website is displayed. 默認每個標簽頁創(chuàng)建一個渲染引擎實例。
? V8 Proxy resolver
關(guān)于V8 Proxy resolver可查看
group.google.com !topic/net-dev/73f9B5vFphI
Chrome支持使用代理腳本為給定的網(wǎng)址選擇代理服務器,包含使用操作系統(tǒng)提供的代理解析程序的多個平臺的回退實現(xiàn)。但默認情況下(iOS除外),它使用內(nèi)置的解析V8執(zhí)行代理腳本(V8 pac)。今天(截至2015年1月),V8 pac在瀏覽器進程中運行。這意味著瀏覽器進程包含一個V8實例,這是一個潛在的安全漏洞。在瀏覽器進程中允許V8還需要瀏覽器進程允許寫入 - 執(zhí)行頁面。
我們關(guān)于將V8 pac遷移到單獨進程的建議包括為解析器創(chuàng)建Mojo服務,從實用程序進程導出該服務,以及從瀏覽器進程創(chuàng)建/連接到該進程。
瀏覽器進程之間主要通過IPC (Inter Process Communication)通信
4.2 Per-frame renderer processes - Site Isolation
Site Isolation is a recently introduced feature in Chrome that runs a separate renderer process for each cross-site iframe. We’ve been talking about one renderer process per tab model which allowed cross-site iframes to run in a single renderer process with sharing memory space between different sites. Running a.com and b.com in the same renderer process might seem okay. The Same Origin Policy is the core security model of the web; it makes sure one site cannot access data from other sites without consent. Bypassing this policy is a primary goal of security attacks. Process isolation is the most effective way to separate sites. With Meltdown and Spectre, it became even more apparent that we need to separate sites using processes. With Site Isolation enabled on desktop by default since Chrome 67, each cross-site iframe in a tab gets a separate renderer process.
每個iframe是單獨的渲染進程
*請認真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。