我正在尝试使用 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 元素是:
最佳答案
您不需要 Selenium 。应用给出伪 before 内容的说明元素它们的值在css样式指令中携带:
此处,.icon-
之后的 2/3 字母字符串,例如acb
映射到包含您的 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)
关于python - 我如何在使用 selenium python 的网站中抓取::之前的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673103/