爬蟲之汽車之家


爬蟲

今日內容

  • 1、爬蟲介紹
  • 2、爬取汽車之家
  • 3、requests
  • 4、bs4
  • 5、內容編碼改為utf-8
    掌握requests /bs4 不考慮驗證碼和性能基本網頁都能爬取
    以后實際工作中這兩個腳本加scrapy框架就可以了

一、爬蟲介紹

* 1、什么事爬蟲
	編寫程序,根據URL獲取網站信息。
	歷史背景:2015年起我國對數據爬取進行了立法
* 2、爬取汽車之家新聞
		a、偽炤瀏覽器向某個地址發送http請求,獲取返回的字符串
	ret = requests.get(
    		url='https://www.autohome.com.cn/news/',
	)
	print(ret.text)
注:ret是一個對象
	request是偽造瀏覽器的行為

	ret.encoding = ret.apparent_encoding
	數據類型轉換(轉換成中文)

	ret.text 按照字符串顯示內容

	ret.content 按照字節顯示

	b、解析:獲取指定內容
		BeautifulSoup 用於把html中的標簽做切割

	bs4解析html格式的字符串
		div = soup.find(name='標簽名')
		div = soup.find(name='標簽名',id='id名')
		div = soup.find(name='標簽名', class_='') class后面有_
		div = soup.find(name='標簽名',attrs={id:'user',class:'page-one'})
	 
		div.text  獲取標簽的文本
		div.attrs  獲取標簽的屬性
		div.get('src') 獲取標簽屬性的值

		li = soup.find_all(name='標簽名')
		li_list  獲取的是列表
		如果要查詢具體的li_list列表的值,必須要下標索引查找
		li_list[0]

request模塊

url:
params: url中傳入參數
data:
json:
headers:  請求頭
cookies:
proxies:封IP 用代理
files: 上傳文件
auth: 基本認證
timeout: 超時時間
   
allow_redirects: True 
是否允許重定向

stream: 下載大文件時
ret = requests.get('http://127.0.0.1:8000/test/', stream=True)

for i in r.iter_content():
#iter_content() 方法表示來邊下載邊存硬盤
 # print(i)

from contextlib import closing

with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
 # 在此處理響應。
 
	for i in r.iter_content():
print(i)
cert: 證書
verify: 確認


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM