日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【爬虫入门】获取响应内容(即读取网页html的源码)

發布時間:2023/12/14 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【爬虫入门】获取响应内容(即读取网页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的源码)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。