python - 我如何在使用 selenium python 的网站中抓取::之前的元素

标签 python selenium testing web-scraping automation

我正在尝试使用 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)

输出:

' '

电话号码位于此处: Phone-number

电话号码的 Inspect 元素是: Inspect Element

最佳答案

您不需要 Selenium 。应用给出伪 before 内容的说明元素它们的值在css样式指令中携带:

enter image description here

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

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

enter image description here

我的方法可能有点冗长,因为我对 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/

相关文章:

python - 在 Pandas 中将字符串转换为时间

python - 在数字周围裁剪可能位于矩形区域内任何地方的正方形区域

java - Selenium Grid 中不同 PC 上具有不同尺寸的屏幕截图

c# - Selenium WebDriver C# 使用 ChromeDriver 和 FirefoxDriver 的完整网站截图

python - 使用 python 下载大 zip 文件

Python:如何替换 int 数组中的所有相同元素?

java - 单击图像时出现 “Element is not clickable at point” - Selenium WebDriver Java

java - Mockito:如何通过模拟测试我的服务?

rest - 没有可用的工作示例来演示 CucumberJS 与 TestCafe 的集成,显示 RestAPI 测试场景,有人可以建议一种方法吗?

ruby-on-rails - 一致的测试错误(Rspec-core 2.14.5)