python - xpath 使用 selenium 什么都不给

标签 python selenium web-scraping css-selectors webdriverwait

我正在尝试获取 addresss 但它们没有给我任何值(value)你能告诉我我在 xpath 中犯了什么错误好请指导我们这是页面链接 https://www.avocats-strasbourg.com/avocat?uid=3340

enter image description here

代码:

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
import pandas as pd

options = Options()
options.add_argument("--no-sandbox")
options.add_argument("start-maximized")
#options.add_experimental_option("detach", True)
webdriver_service = Service("C:\Program Files (x86)\chromedriver.exe") #Your chromedriver path
driver = webdriver.Chrome(service=webdriver_service,options=options)
url = 'https://www.avocats-strasbourg.com/avocat?'
driver.get(url)
data=[]
def main():
    for x in range(44)[2:]:
        select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#edit-filter-ville'))))
        select.select_by_index(x)
        time.sleep(2)
        click_on_search_button = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '(//*[@value="Lancer la recherche"])[1]')))
        driver.execute_script("arguments[0].click();", click_on_search_button)
        
        try:
            page_links = [element.get_attribute('href') for element in 
                          WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.grid-3-small-1-tiny-1 a")))]
        except:
            pass
    
        for link in page_links:
            driver.get(link)
            time.sleep(2)
            
            try:
                address = driver.find_element(By.XPATH, "//span[contains(text(),'Adresse principale :')]/following-sibling::").text
                
            except:
                address=''
            print(address)
main()

最佳答案

尝试使用 javascript executor 并使用以下 css 选择器。 我没有运行 python 脚本,但是使用 Chome Dev 工具,它工作正常。

address = driver.execute_script('return document.querySelector("h3 + span.sousgras").nextSibling.textContent')

enter image description here

关于python - xpath 使用 selenium 什么都不给,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73607133/

相关文章:

python - 使用 Python 2.7 和 selenium 抓取数据并对其进行排序

python - Bottle 模板支持?

python - cython中的缓慢 split

java - 如何通过 "a class"或 "span class"查找元素?

java - 如何从 Selenium Java 中禁用的输入字段中获取文本

python - 使用 BeautifulSoup 抓取 OSHA 网站

R:2019 年更改后的网页抓取 yahoo.finance

python - 如何在 pyenv 中创建一个 post virtualenv hook 来升级 pip 包

python - beautifulsoup 获取站点的所有 url

python - 循环访问 BeautifulSoup 中的元素,但仅输出该元素的子元素