今天有點新的與大家分享,關(guān)于selenium與xpath之間爬數(shù)據(jù)獲取指定位置的時候,方式不一樣哦。
詳情可以看我的代碼,以b站來看好吧:
![](/d/20211017/49e7198bf0257d4d7ec3e2bc3d7d6492.gif)
查看這href元素,如果是xpath,肯定這么寫是沒有問題的:
i.find_element_by_xpath('./a/@href')
但你再selenium里面這樣寫會報錯,所以要改成這樣
i.find_element_by_xpath('./a').get_attribute('href')
這樣方可正確
這是一個小案例,關(guān)于爬取b站音樂視頻,但我的技術(shù)水平有限,無法下載,找不到那個東東
大家如果知道如何下載可以在評論區(qū)留言,嘿嘿
import requests
from selenium.webdriver import Chrome,ChromeOptions
#后面越來越多喜歡用函數(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)
#這個就是再后臺上面運行那個瀏覽器,不在表面上占用你的
option = ChromeOptions()
option.add_argument('--headless')
option.add_argument("--no-sandbox")
#這里也要輸入
browser = Chrome(options=option)
browser.get(url)
#解析那個web熱搜前,按住ctrl+f會在下面出現(xiàn)一個框框,然后改就完事
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')來獲取指定的位置,要報錯,只能這么獲取,查了很久
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)
#運行完事
get_webhot()
這是這個結(jié)果
![](/d/20211017/67a6a29a369a8ca541a4afca6f723e38.gif)
到此這篇關(guān)于selenium與xpath之獲取指定位置的元素的實現(xiàn)的文章就介紹到這了,更多相關(guān)selenium與xpath指定位置元素內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python爬蟲之用Xpath獲取關(guān)鍵標(biāo)簽實現(xiàn)自動評論蓋樓抽獎(二)
- python使用XPath解析數(shù)據(jù)爬取起點小說網(wǎng)數(shù)據(jù)
- python利用xpath爬取網(wǎng)上數(shù)據(jù)并存儲到django模型中
- python Xpath語法的使用
- Python自動化xpath實現(xiàn)自動搶票搶貨
- python selenium xpath定位操作
- Python爬蟲必備之XPath解析庫