欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一文帶你了解Python 四種常見基礎爬蟲方法介紹

 更新時間:2020年12月04日 09:39:21   作者:詭途  
這篇文章主要介紹了一文帶你了解Python 四種常見基礎爬蟲方法介紹,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

一、Urllib方法

Urllib是python內置的HTTP請求庫

import urllib.request
#1.定位抓取的url
url='http://www.baidu.com/'
#2.向目標url發(fā)送請求
response=urllib.request.urlopen(url)
#3.讀取數(shù)據(jù)
data=response.read()
# print(data) #打印出來的數(shù)據(jù)有ASCII碼
print(data.decode('utf-8')) #decode將相應編碼格式的數(shù)據(jù)轉換成字符串
#post請求
import urllib.parse
url='http://www.iqianyue.com/mypost/'
#構建上傳的data
postdata=urllib.parse.urlencode({
 'name':'Jack',
 'pass':'123456'
}).encode('utf-8') #字符串轉化成字節(jié)流數(shù)據(jù)
html=urllib.request.urlopen(url,data=postdata).read()
print(html)
#headers針對檢驗頭信息的反爬機制
import urllib.request
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
request1=urllib.request.Request('https://www.dianping.com/',headers=headers)#Request類構建了一個完整的請求
response1=urllib.request.urlopen(request1).read()
print(response1.decode('utf-8'))

#超時設置+異常處理
import urllib.request
import urllib.error
for i in range(20):
 try:
  response1=urllib.request.urlopen('http://www.ibeifeng.com/',timeout=0.01)
  print('a')
 except urllib.error.URLError as e:
  print(e)
 except BaseException as a: #所有異常的基類
  print(a)

二、requests方法

–Requests是用python語言基于urllib編寫的,采用的是Apache2 Licensed開源協(xié)議的HTTP庫
–urllib還是非常不方便的,而Requests它會比urllib更加方便,可以節(jié)約我們大量的工作。
–requests是python實現(xiàn)的最簡單易用的HTTP庫,建議爬蟲使用requests庫。
–默認安裝好python之后,是沒有安裝requests模塊的,需要單獨通過pip安裝

import requests
#get請求
r=requests.get('https://www.taobao.com/')
#打印字節(jié)流數(shù)據(jù)
# print(r.content)
# print(r.content.decode('utf-8')) #轉碼
print(r.text) #打印文本數(shù)據(jù)

import chardet
#自動獲取到網(wǎng)頁編碼,返回字典類型
print(chardet.detect(r.content))

POST請求實現(xiàn)模擬表單登錄
import requests
#構建上傳到網(wǎng)頁的數(shù)據(jù)
data={
 'name':'Jack',
 'pass':'123456'
}
#帶登陸數(shù)據(jù)發(fā)送請求
r=requests.post('http://www.iqianyue.com/mypost/',data=data)
print(r.text) #打印請求數(shù)據(jù)
#將登錄后的html儲存在本地
f=open('login.html','wb')
f.write(r.content) #寫入字節(jié)流數(shù)據(jù)
f.close()

#針對檢驗頭信息的反爬機制headers
import requests
#構建headers
headers={
 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
r=requests.get('https://www.dianping.com/',headers=headers)
print(r.text)
print(r.status_code) #狀態(tài)403 被攔截了(查看狀態(tài))
#cookies
#跳過登陸,獲取資源
import requests
f=open('cookie.txt','r') #打開cookie文件
#初始化cookies,聲明一個空字典
cookies={}
#按照字符 ; 進行切割讀取,返回列表數(shù)據(jù),然后遍歷
#split():切割函數(shù) strip()去除字符串前后空白
for line in f.read().split(';'):
 #split將參數(shù)設置為1,把字符串切割成兩個部分
 name,value=line.strip().split('=',1)
 #為空字典cookies添加內容
 cookies[name]=value
r=requests.get('http://www.baidu.com',cookies=cookies)
data=r.text
f1=open('baidu.html','w',encoding='utf-8')
f1.write(data)
f1.close()
#設置代理(網(wǎng)站搜索免費代理ip)
#解決網(wǎng)頁封IP的問題
import requests
proxies={
 #'協(xié)議':'ip:端口號'
 'HTTP':'222.83.160.37:61205'
}
req=requests.get('http://www.taobao.com/',proxies=proxies)
print(req.text)

#設置超時
import requests
from requests.exceptions import Timeout
try:
 response = requests.get("http://www.ibeifeng.com ", timeout=0.01)
 print(response.status_code)
except Timeout:
 print('訪問超時!')

三、BS4- BeautifulSoup4解析

from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a  rel="external nofollow" rel="external nofollow" class="sister" id="link1">Elsie</a>,
<a  rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a  rel="external nofollow" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
# #創(chuàng)建一個BS對象
soup=BeautifulSoup(html,'html.parser') #html.parser默認解析器
print(type(soup))
# 結構化輸出
print(soup.prettify())
#1獲取標簽(只能獲取第一條對應的標簽)
print(soup.p) #獲取p標簽
print(soup.a) #獲取a標簽
print(soup.title) #獲取title
#2獲取標簽內容
print(soup.title.string)
print(soup.a.string)
print(soup.body.string) #如果標簽中有多個子標簽返回None
print(soup.head.string) #如果標簽中有一個子標簽返回子標簽里的文本
#3獲取屬性
print(soup.a.attrs) #返回字典
print(soup.a['id']) #得到指定屬性值
#4操作字節(jié)點
print(soup.p.contents) #得到標簽下所有子節(jié)點
print(soup.p.children) #得到標簽下所有子節(jié)點的迭代對象
#5操作父節(jié)點
print(soup.p.parent) #得到標簽p的父節(jié)點其內部的所有內容
print(soup.p.parents) # 得到標簽p的父節(jié)點的迭代對象
#6操作兄弟節(jié)點(同級的節(jié)點)
#next_sibling和previous_sibling分別獲取節(jié)點的下一個和上一個兄弟元素
print(soup.a.next_sibling)
print(soup.a.previous_sibling)

#二.搜索文檔數(shù)
#1標簽名
#查詢所有a標簽
res1=soup.find_all('a')
print(res1)
#獲取所有a標簽下屬性為class="sister"的標簽(
#使用 class 做參數(shù)會導致語法錯誤,這里也要用class_)
print(soup.find_all('a',class_="sister"))
#2正則表達式
import re
#查詢所有包含d字符的標簽
res2=soup.find_all(re.compile('d+'))
print(res2)
#3列表
#查找所有的title標簽和a標簽
res3=soup.find_all(['title','a'])
print(res3)
#4關鍵詞
#查詢屬性id='link1'的標簽
res4=soup.find_all(id='link1')
print(res4)
#5內容匹配
res5=soup.find_all(text='Tillie') #文本匹配
res55=soup.find_all(text=re.compile('Dormouse'))
print(res55)
#6嵌套選擇
print(soup.find_all('p'))
#查看所有p標簽下所有的a標簽
for i in soup.find_all('p'):
 print(i.find_all('a'))

#三.CSS選擇器
#1根據(jù)標簽查詢對象
res6=soup.select('a') #返回列表
print(res6) #得到所有的a標簽
#2根據(jù)ID屬性查詢標簽對象(id用#)
print(soup.select('#link2'))
#3根據(jù)class屬性查詢標簽對象(class用.)
print(soup.select('.sister'))
print(soup.select('.sister')[2].get_text()) #獲取文本內容
#4屬性選擇(獲取a標簽里=href屬性值的標簽)
print(soup.select('a[ rel="external nofollow" rel="external nofollow" ]'))
#5包含選擇(獲取)
print(soup.select('p a#link1'))
#6并列選擇
print(soup.select('a#link1,a#link2'))
#7得到標簽內容
res7=soup.select('p a.sister')
for i in res7:
 print(i.get_text())
#練習:爬取51job主頁12個職位
from bs4 import BeautifulSoup
import requests
url='https://www.51job.com/'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
html=requests.get(url,headers=headers)
data=html.content.decode('gbk')
soup=BeautifulSoup(data,'html.parser')
#獲取span標簽,class_="at"屬性
span=soup.find_all('span',class_="at")
# for i in span:
#  print(i.get_text())
#select方法(CSS選擇器)
span1=soup.select('span[class="at"]')
for m in span1:
 print(m.get_text())

四、XPath語法

XPath 是一門在 XML 文檔中查找信息的語言。
XPath 可用來在 XML 文檔中對元素和屬性進行遍歷

from lxml import etree
text='''
 <html>
  <head>
   <title>春晚</title>
  </head>
  <body>
   <h1 name="title">個人簡介</h1>
   <div name="desc">
    <p name="name">姓名:<span>岳云鵬</span></p>
    <p name="addr">住址:中國 河南</p>
    <p name="info">代表作:五環(huán)之歌</p>
   </div>
'''
#初始化
html=etree.HTML(text)
# result=etree.tostring(html) #字節(jié)流
# print(result.decode('utf-8'))
#查詢所有的p標簽
p_x=html.xpath('//p')
print(p_x)
#查詢所有p標簽的文本,用text只能拿到該標簽下的文本,不包括子標簽
for i in p_x:
 print(i.text) #發(fā)現(xiàn)<span>沒有拿到
#優(yōu)化,用string()拿標簽內部的所有文本
for i in p_x:
 print(i.xpath('string(.)'))
# 查詢所有name屬性的值
attr_name=html.xpath('//@name')
print(attr_name)
#查詢出所有包含name屬性的標簽
attr_name1=html.xpath('//*[@name]')
print(attr_name1)

到此這篇關于一文帶你了解Python 四種常見基礎爬蟲方法介紹的文章就介紹到這了,更多相關Python 基礎爬蟲內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 詳解Golang 與python中的字符串反轉

    詳解Golang 與python中的字符串反轉

    這篇文章主要介紹了詳解Golang 與python中的字符串反轉的相關資料,這里提供了實現(xiàn)的實例以便大家學習理解,需要的朋友可以參考下
    2017-07-07
  • Python繪制組合圖的示例

    Python繪制組合圖的示例

    這篇文章主要介紹了Python如何繪制組合圖,幫助大家更好的利用python繪制圖像,進行數(shù)據(jù)可視化分析,感興趣的朋友可以了解下
    2020-09-09
  • Python將py文件編譯為exe文件

    Python將py文件編譯為exe文件

    大家好,本篇文章主要講的是Python將py文件編譯為exe文件,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-02-02
  • python實現(xiàn)簡單多人聊天室

    python實現(xiàn)簡單多人聊天室

    這篇文章主要為大家詳細介紹了python實現(xiàn)簡單多人聊天室功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-12-12
  • Python Pandas模塊實現(xiàn)數(shù)據(jù)的統(tǒng)計分析的方法

    Python Pandas模塊實現(xiàn)數(shù)據(jù)的統(tǒng)計分析的方法

    在上一篇講了幾個常用的“Pandas”函數(shù)之后,今天小編就為大家介紹一下在數(shù)據(jù)統(tǒng)計分析當中經(jīng)常用到的“Pandas”函數(shù)方法,希望能對大家有所收獲,需要的朋友可以參考下
    2021-06-06
  • numpy數(shù)組廣播的機制

    numpy數(shù)組廣播的機制

    這篇文章主要介紹了numpy數(shù)組廣播的機制,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • Python中的文本相似度的計算方法總結

    Python中的文本相似度的計算方法總結

    在自然語言處理(NLP)領域,文本相似度計算是一個常見的任務,本文為大家整理了Python中的文本相似度常見計算方法,希望對大家有所幫助
    2023-05-05
  • python操作Excel神器openpyxl看這一篇就夠了

    python操作Excel神器openpyxl看這一篇就夠了

    Python使用openpyxl讀寫excel文件這是一個第三方庫,可以處理xlsx格式的Excel文件,下面這篇文章主要給大家介紹了關于python操作Excel神器openpyxl的相關資料,需要的朋友可以參考下
    2023-04-04
  • Python 利用pydub庫操作音頻文件的方法

    Python 利用pydub庫操作音頻文件的方法

    今天小編就為大家分享一篇Python 利用pydub庫操作音頻文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • python中update的基本使用方法詳解

    python中update的基本使用方法詳解

    這篇文章主要介紹了python中update的基本使用方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07

最新評論