目錄
一、目標(biāo)1:使用etree解析數(shù)據(jù)
二、目標(biāo)2:使用xpath爬取指定數(shù)據(jù)
三、目標(biāo)3:提取指定數(shù)據(jù)
?四、網(wǎng)絡(luò)安全小圈子
一、目標(biāo)1:使用etree解析數(shù)據(jù)
其余的不用過(guò)多介紹,前面的練習(xí)都給大家已經(jīng)過(guò)了一遍
def get_page():
url = 'https://www.chinaz.com/'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0",
}
res1 = requests.get(url, headers=headers, timeout=10)
res = res1.content.decode('utf-8')
tree = etree.HTML(res)
其中數(shù)據(jù)解析代碼如下
tree = etree.HTML(res)
對(duì)返回的內(nèi)容進(jìn)行UTF-8解碼,不然會(huì)出現(xiàn)亂碼
res = res1.content.decode('utf-8')
二、目標(biāo)2:使用xpath爬取指定數(shù)據(jù)
我們來(lái)爬一下這幾個(gè)標(biāo)題
?
找上一級(jí)
可以看到他們都在不同li標(biāo)簽下
所以他們的上一級(jí)標(biāo)簽ul相當(dāng)于是我們的列表合集
定位xpath路徑
定位li的xpath路徑
因?yàn)槲覀円@取到ul下所有l(wèi)i列表
?xpath路徑如下
list = tree.xpath('//*[@id="cz"]/div[2]/div[3]/div/div[1]/div[1]/div/div[2]/div[2]/div/ul/li')
打印出來(lái)可以看見(jiàn)
?
三、目標(biāo)3:提取指定數(shù)據(jù)
定位xpath
然后還有3個(gè)標(biāo)簽才到h2標(biāo)簽
?
遍歷每一個(gè)目標(biāo)標(biāo)簽,并轉(zhuǎn)為text()格式
f = open('test', 'w', encoding ='utf-8')
for l in ul_list:
desc = l.xpath('./div/div[1]/a/h2/text()')[0]
print(desc + '\n')
f.write(str(desc) + '\n')
f.close()
運(yùn)行結(jié)果
?
完整代碼
import requests
from lxml import etree
def get_page():
url = 'https://www.chinaz.com/'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0",
}
res1 = requests.get(url, headers=headers, timeout=10)
res = res1.content.decode('utf-8')
tree = etree.HTML(res)
ul_list = tree.xpath('//*[@id="cz"]/div[2]/div[3]/div/div[1]/div[1]/div/div[2]/div[2]/div/ul/li')
f = open('test', 'w', encoding ='utf-8')
for l in ul_list:
desc = l.xpath('./div/div[1]/a/h2/text()')[0]
print(desc + '\n')
f.write(str(desc) + '\n')
f.close()
if __name__ == '__main__':
get_page()
?四、網(wǎng)絡(luò)安全小圈子
README.md · 書半生/網(wǎng)絡(luò)安全知識(shí)體系-實(shí)戰(zhàn)中心 - 碼云 - 開源中國(guó) (gitee.com)https://gitee.com/shubansheng/Treasure_knowledge/blob/master/README.md文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-542599.html
GitHub - BLACKxZONE/Treasure_knowledgehttps://github.com/BLACKxZONE/Treasure_knowledge文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-542599.html
到了這里,關(guān)于【網(wǎng)絡(luò)安全帶你練爬蟲-100練】第11練:xpath快速定位提取數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!