【问题标题】:getting error " ElementNotInteractableException: Message: element not interactable " while using send_key() function in python selenium在 python selenium 中使用 send_key() 函数时出现错误“ElementNotInteractableException:消息:元素不可交互”
【发布时间】:2019-12-29 12:35:52
【问题描述】:

我已尝试使用 CSS 选择器在搜索框中使用 send_key() 函数发送值并提交,以便我获得特定年份的医生表列表,但出现以下错误 “ ElementNotInteractableException:消息:元素不可交互”

下面是我写的代码:

from selenium import webdriver
from bs4 import BeautifulSoup as bs
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time

url = "https://www.mciindia.org/CMS/information-desk/indian-medical-register"
driver = webdriver.Chrome(r"C:\chromedriver.exe")
driver.get(url)

driver.find_element_by_xpath("//a[contains(text(),'Year of Registration')]").click()
driver.find_elements_by_css_selector("input[type='text']")[-1].send_keys("2015")
driver.find_element_by_css_selector("input[value='Submit']").click()

next_page = True
while next_page == True:
    soup = bs(driver.page_source, 'html.parser')
    table1 = soup.find('table',{'id':'doct_info2'})
    try:
        rows = table1.find_all('tr')

        for row in rows:
            if len(row.find_all('td')) == 7:
                data = row.find_all('td')

                link = data[6].click()

                soup2 = bs(link, 'html.parser')
                table2 = soup2.find('table',{'id':'doctorBiodata'})
                rows = table2.find_all('tr')
                print(rows)
    except:
         pass

    time.sleep(5)
    try:
        driver.find_element_by_xpath("//a[contains(text(),'Next')]").click()
    except:
        print ('No more pages')
        next_page=False

driver.close()

【问题讨论】:

  • 你想要2015的整个搜索结果吗?以及每个doctor的全部数据?

标签: python-3.x selenium-webdriver beautifulsoup


【解决方案1】:

下面的代码是第一个10结果。

您可以将length 从10 更改为42354,这是2015 年份的最大值,您将在同一秒内获得out.csv 的文件。

第二个文件data.csv 将包含内部医生的详细信息。

该页面是通过JavaScript 呈现的,因此我在浏览器Developer-Tools 的Network-Table 下找到了XHR 请求。这是JS。

import pandas as pd
import csv
import re
import requests


def Table():
    table = pd.read_json("https://mciindia.org/MCIRest/open/getPaginatedData?service=getPaginatedDoctor&draw=1&columns[0][data]=0&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=1&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=2&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&columns[2][search][regex]=false&columns[3][data]=3&columns[3][name]=&columns[3][searchable]=true&columns[3][orderable]=true&columns[3][search][value]=&columns[3][search][regex]=false&columns[4][data]=4&columns[4][name]=&columns[4][searchable]=true&columns[4][orderable]=true&columns[4][search][value]=&columns[4][search][regex]=false&columns[5][data]=5&columns[5][name]=&columns[5][searchable]=true&columns[5][orderable]=true&columns[5][search][value]=&columns[5][search][regex]=false&columns[6][data]=6&columns[6][name]=&columns[6][searchable]=true&columns[6][orderable]=true&columns[6][search][value]=&columns[6][search][regex]=false&order[0][column]=0&order[0][dir]=asc&start=0&length=10&search[value]=&search[regex]=false&year=2015&_=1577626804003")['data']
    with open('out.csv', 'w', newline="") as f:
        writer = csv.writer(f)
        writer.writerow(
            ['Year Of The Info', 'Registration#', 'State Medical Councils', 'Name', 'FatherName'])
        data = []
        for item in table:
            writer.writerow(item[1:6])
            required = item[6]
            match = re.search(
                r"openDoctorDetailsnew\('([^']*)', '([^']*)'", required)
            data.append(match.group().split("'")[1:4:2])
        print("Data Saved Into out.csv")
    return data


def Details():
    names = []
    items = []
    for doc, val in Table():
        print(f"Extracting DoctorID# {doc}, RegValue# {val}")
        json = {'doctorId': doc, 'regdNoValue': val}
        r = requests.post(
            "https://mciindia.org/MCIRest/open/getDataFromService?service=getDoctorDetailsByIdImr", json=json).json()
        if r.keys() not in names:
            names.append(r.keys())
        items.append(r.values())
    print("Done")
    return names, items


def Save():
    with open('data.csv', 'w', newline="") as d:
        writer = csv.writer(d)
        n, i = Details()
        writer.writerows(n)
        writer.writerows(i)


Save()

检查输出样本out.csv 和data.csv

注意:您必须查看concurrent.futures,以防您对内部数据进行大量抓取。

【讨论】:

  • @NiteshRao :) 欢迎您。这对我来说是非常有趣的任务
  • 您能否在上面的代码中添加 cmets,以便我可以理解您的代码,因为我不知道 json 在 python 中的工作原理以及您从哪里获取“”table = pd.read_json(above_link) "并发布链接
  • 得到这个错误“解码'string'时UTF-8序列中的八位字节无效”如何解决这个问题。
【解决方案2】:

要在文本框中输入值您需要诱导WebDriverWait() 并等待element_to_be_clickable() 并使用send_keys()

要获取表格,您需要诱导WebDriverWait() 并等待表格可见visibility_of_element_located()

代码:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time

url = "https://www.mciindia.org/CMS/information-desk/indian-medical-register"
driver = webdriver.Chrome(r"C:\chromedriver.exe")
driver.get(url)
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//a[text()='Year of Registration']"))).click()
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//input[@id='doctor_year']"))).send_keys("2015")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//button[@id='doctor_year_details']"))).click()
WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"table.table.table-bordered.dataTable.no-footer")))

next_page = True
while next_page == True:
    soup = bs(driver.page_source, 'html.parser')
    table1 = soup.find('table',{'id':'doct_info2'})
    try:
        rows = table1.find_all('tr')

        for row in rows:
            if len(row.find_all('td')) == 7:
                data = row.find_all('td')

                link = data[6].click()

                soup2 = bs(link, 'html.parser')
                table2 = soup2.find('table',{'id':'doctorBiodata'})
                rows = table2.find_all('tr')
                print(rows)
    except:
         pass

    time.sleep(5)
    try:
        driver.find_element_by_xpath("//a[contains(text(),'Next')]").click()
    except:
        print ('No more pages')
        next_page=False

driver.close()

【讨论】:

    【解决方案3】:

    您可以通过请求更快地完成整个事情。更改绘图参数以获取不同的页面。您可以动态添加或删除时间戳参数“_”。将“年份”更改为不同的年份。初始的 json 响应给出了一个记录计数,因此很容易计算一个循环的结束计数,以 500 个批次为单位的所有结果。使用Session 对象来提高循环中多个请求的 tcp 连接重用效率。

    import requests
    import pandas as pd
    
    params = (
        ('service', 'getPaginatedDoctor'),
        ('draw', '1'),
        ('columns[0][data]', '0'),
        ('columns[0][name]', ''),
        ('columns[0][searchable]', 'true'),
        ('columns[0][orderable]', 'true'),
        ('columns[0][search][value]', ''),
        ('columns[0][search][regex]', 'false'),
        ('columns[1][data]', '1'),
        ('columns[1][name]', ''),
        ('columns[1][searchable]', 'true'),
        ('columns[1][orderable]', 'true'),
        ('columns[1][search][value]', ''),
        ('columns[1][search][regex]', 'false'),
        ('columns[2][data]', '2'),
        ('columns[2][name]', ''),
        ('columns[2][searchable]', 'true'),
        ('columns[2][orderable]', 'true'),
        ('columns[2][search][value]', ''),
        ('columns[2][search][regex]', 'false'),
        ('columns[3][data]', '3'),
        ('columns[3][name]', ''),
        ('columns[3][searchable]', 'true'),
        ('columns[3][orderable]', 'true'),
        ('columns[3][search][value]', ''),
        ('columns[3][search][regex]', 'false'),
        ('columns[4][data]', '4'),
        ('columns[4][name]', ''),
        ('columns[4][searchable]', 'true'),
        ('columns[4][orderable]', 'true'),
        ('columns[4][search][value]', ''),
        ('columns[4][search][regex]', 'false'),
        ('columns[5][data]', '5'),
        ('columns[5][name]', ''),
        ('columns[5][searchable]', 'true'),
        ('columns[5][orderable]', 'true'),
        ('columns[5][search][value]', ''),
        ('columns[5][search][regex]', 'false'),
        ('columns[6][data]', '6'),
        ('columns[6][name]', ''),
        ('columns[6][searchable]', 'true'),
        ('columns[6][orderable]', 'true'),
        ('columns[6][search][value]', ''),
        ('columns[6][search][regex]', 'false'),
        ('order[0][column]', '0'),
        ('order[0][dir]', 'asc'),
        ('start', '0'),
        ('length', '500'),
        ('search[value]', ''),
        ('search[regex]', 'false'),
        ('name', ''),
        ('registrationNo', ''),
        ('smcId', ''),
        ('year', '2015'),
        ('_', '1577634512046'),
    )
    
    table_headers = ['Sl. No.','Year of Info','Registration Number','State Medical Councils','Name','Father Name','Action']
    r = requests.get('https://mciindia.org/MCIRest/open/getPaginatedData',  params=params)
    df = pd.DataFrame(r.json()['data'], columns = table_headers)
    print(df)
    

    【讨论】:

    • 检查我的答案
    • 我在大约 2 小时前完成了代码,但正在检查 TCPdump 以便一次性获取内部医生详细信息。实际上,OP 正在全面了解内部医生的详细信息,您可以通过单击 View 按钮查看。
    • tbh 我没有费心玩参数,但看起来你可以删除很多
    • 是的,空值可以关闭。但对于内部表。不一样sharecsv.com/s/e64642cd1cc053f8faf9a11adf853ecf/data.csv
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多