【爬虫入门】获取响应内容(即读取网页html的源码)
生活随笔
收集整理的這篇文章主要介紹了
【爬虫入门】获取响应内容(即读取网页html的源码)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在現實應用中,網絡爬蟲獲取網頁數據的流程如下:
(1)模擬瀏覽器發送請求
(2)獲取響應內容(獲取網頁):即獲取html、css、json、圖片、音頻、視頻等類型信息
(3)解析內容(提取信息):正則表達式、第三庫解析庫(Beautifulsoup、pyquery等)
(4)保存數據:保存到數據庫(mysql、mongdb、redis等)或txt、csv、json、xml…格式的文件
- 注意:本編內容主要是上述的(1)和(2)步驟。
方法一:requests.get 無標注解析器
# python3.6import requestsurl = "https://www.163.com" headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.100.4811.0 Safari/537.36" } res = requests.get(url, headers=headers) str_content = res.text byte_content = res.content print(type(str_content), type(byte_content)) # <class 'str'> <class 'bytes'>方法二:requests.get 有標注解析器
# python3.6import requestsurl = "https://www.163.com" headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.100.4811.0 Safari/537.36" } res = requests.get(url,'lxml',headers=headers) str_content = res.text byte_content = res.content print(str_content) print(type(str_content),type(byte_content)) # <class 'str'> <class 'bytes'>方法三:urllib.request.urlopen
# python3.6from urllib import requesturl = "https://www.163.com" headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.100.4811.0 Safari/537.36" } res = request.urlopen(request.Request(url, headers=headers)) # 以下代碼,二選一 bytes_content = res.read() str_content = res.read().decode('utf-8') # bytes數據類型,需要utf-8解碼 print(type(bytes_content), type(str_content)) # <class 'bytes'> <class 'str'>方法四:urllib3
# python3.6import urllib3url = "https://www.163.com" headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.100.4811.0 Safari/537.36" } http = urllib3.PoolManager() res = http.request('GET', url, headers=headers) bytes_content = res.data str_content = res.data.decode('utf-8') # bytes數據類型,需要解碼 print(bytes_content) print(type(bytes_content), type(str_content)) # <class 'bytes'> <class 'str'>總結
以上是生活随笔為你收集整理的【爬虫入门】获取响应内容(即读取网页html的源码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阳台山之登山攻略
- 下一篇: selenium源码通读·5 |webd