如何使用 selenium python 在网站中抓取 ::before 元素

5 python testing selenium automation web-scraping

我正在尝试使用硒从该网站上抓取电话号码。我发现这个类是“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)
Run Code Online (Sandbox Code Playgroud)

输出:

' '

电话号码在这里: 电话号码

电话号码的 Inspect 元素是: 检查元素

QHa*_*arr 4

你不需要硒。应用内容的指令在 css 样式指令中携带伪元素之前的值:

在此输入图像描述

.icon-在这里, eg后面的 2/3 字母字符串acb映射到span容纳您的before内容的元素。后面的值\9d0是显示的实际值的 + 1。您可以根据这些值对(经过调整)创建一个字典,以beforespan类值中解码每个值的数字。

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)
Run Code Online (Sandbox Code Playgroud)