單行注釋#
爬蟲需要掌握的技術(shù)
1. python基礎(chǔ)語法
2. HTML結(jié)構(gòu)
3. 爬蟲模塊的使用
爬蟲相關(guān)
安裝requests
pip install requests
(手動(dòng)安裝File——Settings——Project Interpreter——+——install)
1.獲取到網(wǎng)頁的源代碼 requests
代碼示例
import requests
# 獲取指定域名的源代碼
response = requests.get('https://www.baidu.com')
# 響應(yīng)狀態(tài)碼 200 ok 404 not found
print(response.status_code)
# 相應(yīng)的編碼方式
# 設(shè)置編碼方式
response.encoding = 'utf-8'
print(response.status_code)
print(response.encoding)
# 獲取 string類型的響應(yīng)
html_data = response.text
print(html_data)
# 將 爬取的文件寫成 本地 html
# 文件路徑 讀寫模式 編碼方式
with open('index.html','w',encoding='utf-8') as f:#爬網(wǎng)頁源碼
if response2.status_code == 200:
f.write(html_data)
圖片的爬取
代碼示例
import requests
# 圖片地址
#F12——左上角選擇元素——src以后的網(wǎng)址 =url
`
url = 'http://imgsrc.baidu.com/forum/pic/item/00eaa0ec08fa513d1a4e0fbe326d55fbb3fbd94b.jpg'
response2 = requests.get(url)
# 獲取byte類型的響應(yīng)
img_data = response2.content
# 文件路徑 讀寫模式 編程方式
with open('tupian.png','wb') as f: #爬網(wǎng)頁圖片
if response2.status_code == 200:
f.write(img_data)
2.然后提取我們要的信息 xpath
使用xpath語法提取本地html文件的內(nèi)容
代碼示例
# 安裝lxml庫
# pip install lxml
from lxml import html
讀取本地的html文件
with open('路徑','模式','編碼') as f:
f.write('寫入的內(nèi)容')
f.read() # 讀取模式
with open('index2.html','r',enconding='utf-8')as f:
# f.write('寫入的內(nèi)容')
html_data = f.read() # 讀取模式
print(html_data)
提取h1標(biāo)題中的內(nèi)容
selector = html.fromstring(html_data)
# 獲取標(biāo)簽的內(nèi)容需要在路徑末尾增加/text()
# /代表根節(jié)點(diǎn)
h1 = selector.xpath('/html/boby/h1/text()')
print(h1)
語法形式
//標(biāo)簽1[@屬性='屬性值']/標(biāo)簽2[@屬性='屬性值']/.../text()
//從任意位置開始
獲取a標(biāo)簽的內(nèi)容
a = selector.xpath('//div[@id="container"]/a/text()')
print(a)
獲取標(biāo)簽屬性語法形式
//標(biāo)簽1[@屬性='屬性值']/標(biāo)簽2[@屬性='屬性值']/.../@屬性名
link = selector.xpath('//div[@id="container"]/a/@href')
print(link)