一、python爬蟲手法
- 正則匹配:難度較大,不建議
-
BeautifulSoup或者xpath:文檔結(jié)構(gòu)清晰【推薦】
實(shí)際使用常常是:BeautifulSoup或者xpath匹配到對應(yīng)的dom節(jié)點(diǎn),然后正則提取想要的數(shù)據(jù)
二、BeautifulSoup / xpath 安裝使用
(1)BeautifulSoup :
安裝:pip install lxml
pip install bs4
使用:文章來源:http://www.zghlxwxcb.cn/news/detail-475947.html
from bs4 import beautifulsoup
soup = BeautifulSoup(html, 'lxml') # html是網(wǎng)頁文本
p_list = soup.select('p')
三、BeautifulSoup 語法精髓
- 提供的用于數(shù)據(jù)解析的方法和屬性:
- soup.tagName:返回的是文檔中第一次出現(xiàn)的tagName對應(yīng)的標(biāo)簽(html標(biāo)簽)
- soup.find():
- find('tagName'):等同于soup.div
- 屬性定位:
- soup.find('div',class_/id/attr='attrName'):返回符合要求的第一個(gè)標(biāo)簽
- soup.find_all('tagName'):返回符合要求的所有標(biāo)簽(列表)
- select:
- select('某種選擇器(id,class,標(biāo)簽.·,選擇器)·),返回的是一個(gè)列表。
- 層級選擇器:
- soup.select('.className > ul > li > a'): >表示的是一個(gè)層級
- soup.select('.className > ul a'):空格表示的多個(gè)層級
- 獲取標(biāo)簽之間的文本數(shù)據(jù):
- soup.a.text/string/get_text()
- text/get_text():可以獲取某一個(gè)標(biāo)簽中所有的文本內(nèi)容
- string:只可以獲取該標(biāo)簽下面直系的文本內(nèi)容
- 獲取標(biāo)簽中屬性值:
- soup.a['href '
四、xpath語法精髓
- 環(huán)境的安裝:
- pip install lxml
- 如何實(shí)例化一個(gè)etree對象:from lxml import etree
- 1.將本地的htmL文檔中的源碼數(shù)據(jù)加載到etree對象中:
etree.parse(filePath)
- 2.可以將從互聯(lián)網(wǎng)上獲取的源碼數(shù)據(jù)加載到該對象中
etree.HTML('page_text')
xpath('xpath表達(dá)式')
- xpath表達(dá)式【和linux的文件路徑操作一樣】:
- / : 根節(jié)點(diǎn),節(jié)點(diǎn)分隔符,
- // : 任意位置,可以是多個(gè)層級
- . 當(dāng)前節(jié)點(diǎn)
- .. 父級節(jié)點(diǎn)
- @ 屬性定位,如:/div[@class='className'] tag[@attrName="attrValue"]
- 索引定位: //div[@class="className"]/p[3]: 索引是從1開始的
- 取文本:
- /text()獲取的是標(biāo)簽中直系的文本內(nèi)容
- //text()標(biāo)簽中非直系的文本內(nèi)容(所有的文本內(nèi)容)
- 取屬性:
- /dattrName ==> img/src
五、爬蟲例子代碼
爬取國家重點(diǎn)保護(hù)野生植物的信息,網(wǎng)站:中國珍稀瀕危植物信息系統(tǒng)文章來源地址http://www.zghlxwxcb.cn/news/detail-475947.html
import json
from bs4 import BeautifulSoup
from lxml import etree
import requests
import re
def request_url(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
}
try:
response = requests.get(url, headers = headers)
if response.status_code == 200:
return response.text
except requests.RequestException as e:
print('===>>>請求異常' + e)
return None
def parse_result(html):
"""使用BeautifulSoup進(jìn)行解析html"""
soup = BeautifulSoup(html, 'lxml')
tr_list = soup.select('tr')
for tr in tr_list:
print("解析結(jié)果:" + str(tr))
td_items = tr.select('.td2')
if len(td_items) == 0:
continue
yield {
'中文名': re.sub('\s', '', td_items[0].text),
'拉丁名': re.sub('\s', '', td_items[1].text),
'科名': re.sub('\s', '', td_items[2].text),
'I級': re.sub('\s', '', td_items[3].text),
'II級': re.sub('\s', '', td_items[4].text),
}
def xpath_parse_result(html):
"""使用xpath進(jìn)行解析html"""
html_doc = etree.HTML(html)
tr_list = html_doc.xpath('//body/form/div[@class="divmenuh"]//table[@class="table1"]//tr')
for tr in tr_list:
print("解析結(jié)果:" + str(tr))
td_items = tr.xpath("./td[@class='td2']")
if len(td_items) == 0:
continue
yield {
'中文名': re.sub('\s', '', td_items[0].xpath(".//text()")[0]),
'拉丁名': re.sub('\s', '', td_items[1].xpath(".//text()")[0]),
'科名': re.sub('\s', '', td_items[2].xpath(".//text()")[0]),
'I級': re.sub('\s', '', td_items[3].xpath(".//text()")[0]),
'II級': re.sub('\s', '', td_items[4].xpath(".//text()")[0]),
}
def plant_spider(page):
url = 'http://www.iplant.cn/rep/protlist?page=' + str(page)
html = request_url(url)
if None == html:
print("===>>>請求失?。? + url)
return
items = parse_result(html) # 解析過濾我們想要的信息
# items = xpath_parse_result(html) # 使用xpath進(jìn)行解析
with open('國家重點(diǎn)保護(hù)野生植物(2021版).txt', 'a', encoding='UTF-8') as f:
for item in items:
print('開始寫入數(shù)據(jù) ====> ' + str(item))
f.write(json.dumps(item, ensure_ascii=False) + '\n')
if __name__ == "__main__":
# 爬取國家重點(diǎn)保護(hù)野生植物的信息
for i in range(1, 58):
plant_spider(i)
到了這里,關(guān)于python簡單網(wǎng)頁爬蟲的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!