[英]How do I scrape ::before element in a website using BeautifulSoup?
[英]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.