工作中有批量獲取網(wǎng)頁head中title的應(yīng)用場(chǎng)景,實(shí)踐中遇到了一些問題,以此記錄一下。
-
通過檢查發(fā)現(xiàn)網(wǎng)頁的head中的title確實(shí)有文本,但是使用selenium的driver.title提取到了空字符串’’
-
接著使用driver.find_element(By.XPATH, ‘/html/head/title’).is_displayed(),得到False,說明title被隱藏了
-
進(jìn)一步檢查一下head,使用
js = "document.head" print(driver.execute_script(js))# 得到None js = "document.title" print(driver.execute_script(js))# 同樣是None
說明head整個(gè)給隱藏了?
-
開始百度谷歌,嘗試使用了css選擇器,XPATH定位等,嘗試了bs4解析網(wǎng)頁,添加js 語句去使head displayed設(shè)置維True等等,都失敗了,得到同樣結(jié)果。文章來源:http://www.zghlxwxcb.cn/news/detail-535950.html
解決方法
最終找到了一個(gè)方法解決了問題。
代碼如下,利用XPATH先定位元素,然后get_attribute(“textContent”)可以獲得到隱藏的元素,前面的定位器應(yīng)該也可以改成自己所需要的其他定位。文章來源地址http://www.zghlxwxcb.cn/news/detail-535950.html
driver.find_element(By.XPATH, '/html/head/title').get_attribute("textContent")
完整代碼如下
# 返回網(wǎng)站名稱列表,數(shù)據(jù)來源列表
def get_site_name(urls,site_names):
options = webdriver.ChromeOptions()
options.page_load_strategy = 'none' # 我只要部分html元素,所以選擇不渲染全部html內(nèi)容
driver = webdriver.Chrome('C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe', options=options) # 自己的路徑
driver.maximize_window() # 最大化窗口
# wait = WebDriverWait(driver, 5)
names = []
state = []
for i in tqdm(range(len(urls))):
url = urls[i]
try:
driver.get(url)
# wait.until(driver.find_element(By.XPATH, '/html/head/title'))
time.sleep(1) # 一定要sleep 1s,不然會(huì)找不到元素,也就是要等待網(wǎng)頁打開才行
title = driver.find_element(By.XPATH, '/html/head/title').get_attribute("textContent")
names.append(title)
state.append(1) # 代表獲取成功
except:
names.append(site_names[i])
state.append(0) # 代表獲取失敗
return pd.DataFrame({'url':urls,'site_name':site_names,'title':names,'state':state})
到了這里,關(guān)于python利用selenium獲取網(wǎng)頁head中的title的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!