Why Selenium webdriver won't populate form - visual-studio-code

I've got some code that was intended to logon using selenium( selenium-4.7.2) so that I can keep up with job alerts on a popular job site. It's also a means of keeping my skills up while seeking work.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.service import Service
#from webdriver_manager.chrome import ChromeDriverManager
#driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Set up the webdriver
driver = webdriver.Chrome()
# Navigate to the login page
driver.get('https://www.linkedin.com/uas/login')
# Enter your login credentials
driver.find_element_by_id('username').send_keys('elksie#gmail.com')
driver.find_element_by_id('password').send_keys('g')
# Click the "Sign in" button
driver.find_element_by_css_selector('button[type="submit"]').click()
# Wait for the page to load
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'jobs-search-box')))
# Navigate to the job search page
driver.get('https://www.linkedin.com/jobs/search/?currentJobId=3424225432&keywords=data%20analyst&refresh=true')
# Wait for the page to load
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'job-card-container')))
# Extract the job data
job_cards = driver.find_elements_by_class_name('job-card-container')
for job_card in job_cards:
title = job_card.find_element_by_class_name('job-card-container__title').text
company = job_card.find_element_by_class_name('job-card-container__subtitle').text
location = job_card.find_element_by_class_name('job-card-container__bullet').text
print(title, company, location)
# Close the browser
driver.close()
The lines...
driver.find_element_by_id('username').send_keys('elksie#gmail.com')
driver.find_element_by_id('password').send_keys('g')
errors with:
AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'

find_element_by_id has been deprecated. Use driver.find_element(By.ID, 'username')
Import By using:
from selenium.webdriver.common.by import By

Related

How to get user ID through mentioning Telegram bot python

I write code for Replit.com
i make a command /add_administrator that is, Ana must add the user ID of the user I mentioned to the file admins.json but after using the command the bot breaks What I understand the bot sees(/add_administrator)
(#user)ignore or not see
I would like to understand how to get the user id through a #mention
It will be in a different language full code :https://github.com/jonoto2/TeleBotPHP/blob/main/main.py
complete command code:
from webserver import keep_alive
import json
import random
import re
import os
import telebot
from telebot import types
#from telegram.ext import Updater
bot = telebot.TeleBot(os.environ['TOKEN'], parse_mode="HTML")
#bot.message_handler(commands=['add_adm'])
def add_adm(message):
# Check if user is admin
if is_admin(int(message.from_user.id)):
args = get_args(message.text)
# Check for args
if args and args[0].isdigit():
id = int(args[0])
with open('admins.json', "r") as jsonFile:
data = json.load(jsonFile)
if id not in data:
data.append(id)
with open("admins.json", "w") as jsonFile:
json.dump(data, jsonFile)
bot.reply_to(message, f"`{id}` Appointed as admin.")
else:
bot.reply_to(message,
'This user is already an administrator .')
else:
bot.reply_to(message, 'User is not found.')
else:
bot.reply_to(message, 'You are not an administrator .')
I have not tried anything because I do not understand how

Unable to start Appium server programmatically

I am trying to start the Appium server using Appium service builder but am getting the following error. I tried everything but still get the error.
AppiumTest
io.appium.java_client.service.local.AppiumServerHasNotBeenStartedLocallyException: The local appium server has not been started. The given Node.js executable: C:\Program Files\nodejs\node.exe Arguments: [C:\Users\[username]\AppData\Roaming\npm\node_modules\appium\build\lib\main.js, --port, 4723, --address, 127.0.0.1]
at io.appium.java_client.service.local.AppiumDriverLocalService.start(AppiumDriverLocalService.java:191)
package MahiyarAutomation;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
public class AppiumBasics {
#Test
public void AppiumTest() throws MalformedURLException
{
AppiumDriverLocalService service = new AppiumServiceBuilder().withAppiumJS(new File("C:\\Users\\mahiyarwadia\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js"))
.withIPAddress("127.0.0.1").usingPort(4723).build();
service.start();
UiAutomator2Options options = new UiAutomator2Options();
options.setDeviceName ("MahiyarPhone");
options.setApp ("//Users//mahiyarwadia//eclipse-workspace//Appium//src//test//java//resources//ApiDemos-debug.apk");
}
}
Could you try the following?
AppiumServiceBuilder builder = new AppiumServiceBuilder()
.withAppiumJS(new File("C:\\Users\\mahiyarwadia\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js"))
.withIPAddress("127.0.0.1")
.usingPort(4723);
AppiumDriverLocalService service = AppiumDriverLocalService.buildService(builder);
service.start();
If it still does not work:
Are you able to start the server via the GUI or command line?
Is the Appium path correct?

When execute the test script in appium it display AttributeError: can't set attribute

import time
import ScrollUtil
from appium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['deviceName'] = 'Android'
desired_caps['appPackage'] = 'com.samsung.android.dialer'
desired_caps['appActivity'] = 'com.samsung.android.dialer.DialtactsActivity'
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
driver.implicitly_wait(10)
ScrollUtil.swipeUp(4,driver)
ScrollUtil.swipeDown(4,driver)
# driver.find_element_by_android_uiautomator(
# 'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains("Akash").instance(0))').click()
time.sleep(2)
driver.quit()
`
When I execute the above scripts I receive the below error messages and cannot be executed. I have already open the Appium Server
self.capabilities = response.get('value')
AttributeError: can't set attribute
Error message
Reinstall Appium-Python-Client using pip, instead of npm
And make sure selenium 3.XX version is installed

persistent issue with PyQt6 QtWebEngine

In Chrome, if you close the pop up dialog of this page, then it won't show if you open the page again. However, in my following code, the pop up dialog still shows in a second run even you close it in the first run, it seems to be a issue with the persistent storage, but I don't know how to solve the issue, any help?
from PyQt6.QtCore import *
from PyQt6.QtCore import pyqtSlot as Slot
from PyQt6.QtCore import pyqtSignal as Signal
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from PyQt6.QtWebEngineWidgets import *
from PyQt6.QtWebEngineCore import *
import sys
import os
class WebEngineView(QWebEngineView): # QWebEngineView
def __init__(self, parent=None):
super().__init__(parent)
self.webpage = QWebEnginePage()
# self.webpage.javaScriptConsoleMessage = lambda level, message, lineNumber, sourceID: print(message) # if level > QWebEnginePage.WarningMessageLevel else None # 关闭js console msg,不起作用→self.javaScriptConsoleMessage = None;https://doc.qt.io/qt-5/qwebenginepage.html#JavaScriptConsoleMessageLevel-enum
self.setPage(self.webpage)
self.webpage.load(QUrl('https://fanyi.baidu.com/'))
if __name__ == "__main__":
app = QApplication(sys.argv)
webEngineView = WebEngineView()
webEngineView.showMaximized()
sys.exit(app.exec())
My solotion:
from PyQt6.QtCore import *
from PyQt6.QtCore import pyqtSlot as Slot
from PyQt6.QtCore import pyqtSignal as Signal
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from PyQt6.QtWebEngineWidgets import *
from PyQt6.QtWebEngineCore import *
import sys
import os
class WebEnginePage(QWebEnginePage): # QWebEngineView
def __init__(self, profile, parent=None):
super().__init__(profile, parent)
def contextMenuEvent(self, event): # 算是一种折中的方法,因为其他的方法好像因为bug的原因不起作用
self.menu = self.createStandardContextMenu() # page().
selectedText = self.selectedText()
if selectedText:
self.menu.addSeparator()
self.menu.addAction('谷歌搜索', lambda: QDesktopServices.openUrl(QUrl(f'https://www.google.com/search?q={selectedText}')))
self.menu.popup(event.globalPos()) # 这种貌似怪异的做法也不能改成show或pos;using menu.exec() might lead to consolle warnings and painting artifacts, so using popup() is better
class WebEngineView(QWebEngineView): # QWebEngineView
def __init__(self, parent=None):
super().__init__(parent)
self.webEngineProfile = QWebEngineProfile('EngkudictWebEngineProfile ')
# self.webEngineProfile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.ForcePersistentCookies)
print(self.webEngineProfile.persistentCookiesPolicy(), self.webEngineProfile.isOffTheRecord())
self.webpage = WebEnginePage(self.webEngineProfile) # QWebEnginePage(self.webEngineProfile)
# self.webpage.destroyed.connect(lambda obj: self.webEngineProfile.deleteLater()) #这种方式不行 If the profile is not the default profile, the caller must ensure that the profile stays alive for as long as the page does.
self.setPage(self.webpage)
self.webpage.load(QUrl('https://fanyi.baidu.com/'))
# webEngineProfile = self.page().profile()
# # webEngineProfile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.ForcePersistentCookies)
# print(webEngineProfile.persistentCookiesPolicy(), webEngineProfile.isOffTheRecord(), webEngineProfile.persistentStoragePath()) # Qt6 PersistentCookiesPolicy.NoPersistentCookies True=====Qt6 1 False
# # self.load(QUrl('https://fanyi.baidu.com/'))
# self.load(QUrl('https://doc.qt.io/qt-6/qwebengineprofile.html#QWebEngineProfile-1'))
#Slot(QCloseEvent)
def closeEvent(self, event):
self.setPage(None) # To avoid msg: Release of profile requested but WebEnginePage still not deleted. Expect troubles ! https://github.com/qutebrowser/qutebrowser/commit/e6ae8797e71a678bef97a13b9057e29442e0ef48
# del self.webEngineProfile
# self.webEngineProfile.deleteLater() # A disk-based QWebEngineProfile should be destroyed on or before application exit, otherwise the cache and persistent data may not be fully flushed to disk. https://doc.qt.io/qt-6/qwebengineprofile.html#QWebEngineProfile-1
if __name__ == "__main__":
# QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling) # 任务Qt6 不需要了Qt High DPI scaling is now activated by default; the default rounding policy is PassThrough
# os.putenv("QT_ENABLE_HIGHDPI_SCALING", '1')
os.putenv("QT_SCALE_FACTOR", '1.6')
app = QApplication(sys.argv)
webEngineView = WebEngineView()
webEngineView.showMaximized()
sys.exit(app.exec())

`basename` argument not specified

i created a new project by django restframework
the project name = frame
th project_app name= framework
fram.urls.py:
"""frame URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from django.conf.urls import include,url
from framework.views import myviewset
from rest_framework import routers
router = routers.DefaultRouter();
router.register('task', myviewset)
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'', include(router.urls)),
]
framework models.py:
from django.db import models
# Create your models here.
class Task (models.Model):
task_name=models.CharField(max_length='200')
task_desc=models.CharField(max_length='200')
date_created=models.DateTimeField(auto_now=True)
serializer.py
from .models import Task
from rest_framework import serializers
class TaskSerializers(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id', 'task_name', 'task_desc')
views.py:
from django.shortcuts import render
from .serializer import TaskSerializers
from rest_framework import viewsets
from .models import Task
# Create your views here.
class myviewset(viewsets.ModelViewSet):
query = Task.objects.all().order_by('date_created')
serializer_class = TaskSerializers
admin.py:
from django.contrib import admin
from .models import Task
admin.site.register(Task)
# Register your models here.
setting.py:
INSTALLED_APPS = [
'framework',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
when i run th server in CMD
this error comes :
AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.
You should specify queryset attribute instead of query in your viewset. For example (class name case changed to comply PEP8):
class MyViewSet(viewsets.ModelViewSet):
queryset = Task.objects.all().order_by('date_created')
serializer_class = TaskSerializers
Docs: https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset
Also I recommend always specify basename when you register your viewsets. Like this:
router = routers.DefaultRouter();
router.register('task', MyViewSet, basename='tasks')
https://www.django-rest-framework.org/api-guide/routers/#usage
basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.