簡體   English   中英

如何使用selenium python在網站中刪除::之前的元素

[英]How do I scrape ::before element in a website using selenium python

我正在嘗試使用selenium從這個網站上搜索電話號碼。 我發現這個課程是“tel ttel”,但當我嘗試通過find_element_by_xpath抓取網站時。 我得到一個空字符串。

我的代碼:

wd = webdriver.Chrome(chrome_path)
url = 'https://www.justdial.com/Bangalore/Spardha-Mithra-IAS-KAS-Coaching-Centre-Opposite-Maruthi-Medicals-Vijayanagar/080PXX80-XX80-140120184741-R6P8_BZDET?xid=QmFuZ2Fsb3JlIEJhbmsgRXhhbSBUdXRvcmlhbHM='
wd.get(url)
phone = wd.find_element_by_xpath('//a[@class="tel ttel"]').text
print(phone)

輸出:

''

電話號碼位於此處: 電話號碼

電話號碼的Inspect元素是: 檢查元素

你不需要硒。 應用內容的說明為css樣式指令提供了偽值前面元素的值:

在此輸入圖像描述

這里, .icon-例如acb之后的2/3字母字符串映射到容納您before內容的span元素。 \\9d0之后的值是顯示的實際值的+ 1。 您可以從這些值對(通過調整)創建字典,以解碼span類值before的每個數字。

2/3字母字符串如何映射到內容的示例:

在此輸入圖像描述

我的方法可能有點冗長,因為我不熟悉Python,但邏輯應該清楚。

import requests
import re
from bs4 import BeautifulSoup
url = 'https://www.justdial.com/Bangalore/Spardha-Mithra-IAS-KAS-Coaching-Centre-Opposite-Maruthi-Medicals-Vijayanagar/080PXX80-XX80-140120184741-R6P8_BZDET?xid=QmFuZ2Fsb3JlIEJhbmsgRXhhbSBUdXRvcmlhbHM='
res  = requests.get(url, headers  = {'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(res.content, 'lxml')

cipherKey = str(soup.select('style[type="text/css"]')[1])
keys = re.findall('-(\w+):before', cipherKey, flags=0)
values = [int(item)-1 for item in re.findall('9d0(\d+)', cipherKey, flags=0)]
cipherDict = dict(zip(keys,values))
cipherDict[list(cipherDict.keys())[list(cipherDict.values()).index(10)]] = '+'
decodeElements = [item['class'][1].replace('icon-','') for item in soup.select('.telCntct span[class*="icon"]')]

telephoneNumber = ''.join([str(cipherDict.get(i)) for i in decodeElements])
print(telephoneNumber)

您還可以在計算樣式的內容:before獲取:

chars = driver.execute_script("return [...document.querySelectorAll('.telCntct a.tel span')].map(span => window.getComputedStyle(span,':before').content)")

但在這種情況下,你會留下奇怪的unicode內容,然后你必須映射到數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM