今天有點(diǎn)新的與大家分享,關(guān)于selenium與xpath之間爬數(shù)據(jù)獲取指定位置的時(shí)候,方式不一樣哦。
詳情可以看我的代碼,以b站來看好吧:
查看這href元素,如果是xpath,肯定這么寫是沒有問題的:
i.find_element_by_xpath('./a/@href')
但你再selenium里面這樣寫會報(bào)錯(cuò),所以要改成這樣
i.find_element_by_xpath('./a').get_attribute('href')
這樣方可正確
這是一個(gè)小案例,關(guān)于爬取b站音樂視頻,但我的技術(shù)水平有限,無法下載,找不到那個(gè)東東
大家如果知道如何下載可以在評論區(qū)留言,嘿嘿
import requests from selenium.webdriver import Chrome,ChromeOptions #后面越來越多喜歡用函數(shù)來實(shí)現(xiàn)了 def get_webhot(): #熱搜函數(shù) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36' } url ="https://www.bilibili.com/" # 微博的地址 res = requests.get(url) #這個(gè)就是再后臺上面運(yùn)行那個(gè)瀏覽器,不在表面上占用你的 option = ChromeOptions() option.add_argument('--headless') option.add_argument("--no-sandbox") #這里也要輸入 browser = Chrome(options=option) browser.get(url) #解析那個(gè)web熱搜前,按住ctrl+f會在下面出現(xiàn)一個(gè)框框,然后改就完事 browser.find_element_by_xpath('//*[@id="primaryChannelMenu"]/span[3]/div/a/span').click() c = browser.find_elements_by_xpath('//*[@id="high_energy"]/div[1]/div[2]/div') for i in c: #這里一定要注意,在selenium中不能像xpath那樣寫('./a/@href')來獲取指定的位置,要報(bào)錯(cuò),只能這么獲取,查了很久 detail_url = i.find_element_by_xpath('./a').get_attribute('href') name = i.find_element_by_xpath('./a/p').get_attribute('title') detail_page_text = requests.get(url=detail_url,headers = headers).text print(detail_url,name) #運(yùn)行完事 get_webhot()
這是這個(gè)結(jié)果
到此這篇關(guān)于selenium與xpath之獲取指定位置的元素的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)selenium與xpath指定位置元素內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:東莞 漢中 德宏 重慶 河池 臨汾 廊坊 長春
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《selenium與xpath之獲取指定位置的元素的實(shí)現(xiàn)》,本文關(guān)鍵詞 selenium,與,xpath,之,獲取,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。