Category Archives: Python

Solve the problem of Command “python setup.py egg_info” failed with error code 1

reference:

“Pip install unroll”: “python setup.py egg_info” failed with error code 1

Solve the problem of Command “python setup.py egg_info” failed with error code 1

In the execution pip install -r requirements.txtencountered an error when:

Command "python setup.py egg_info" failed with error code 1

The solution is to update setuptools and pip:

pip install --upgrade setuptools
python -m pip install --upgrade pip

 

Four ways to solve selenium’s error “element is not clickable at point…”

Click to report an error

When using selenium, click events are triggered, and the following exceptions are often reported:

Element is not clickable at point

Causes and Solutions

There are four reasons

1. Not loaded

Wait for the element to be loaded before proceeding
you can use the python library

import time 
time.sleep(3)

But it’s better to use selenium’s own webdriverwait

from selenium.webdriver.support.ui import WebDriverWait

WebDriverWait(driver, 10).until(EC.title_contains("element"))

For the specific usage of webdriverwait, please click the reference document

2. In iframe

If the element is in the iframe, you can’t find it in the window, and you can’t click it. So, switch to iframe to find the element

driver.switch_to_frame("frameName")  # Switching by frame name
driver.switch_to_frame("frameName.0.child") # child frame
driver.switch_to_default_content() # return

For other related switching, please click the reference document

3. Not in the window, need to pull the scroll bar

The list page of many websites does not return all the contents immediately, but is displayed according to the view. Therefore, we need to drag the scroll bar to display the content to be obtained in the window

page = driver.find_element_by_partial_link_text(u'next page')
driver.execute_script("arguments[0].scrollIntoView(false);", page)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, u'next page'))).click()

About the contents of the drop-down scroll bar, please refer to the blog

4. The element to be clicked is covered

You can use the event chain to solve
problems, such as drop-down menus, which can be displayed through the hover, and then you can click

menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")

ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()

For details of the event chain, please click document

InvalidSelectorError: Compound class names not permitted [How to Solve]

InvalidSelectorError: Compound class names not permitted报错处理

Environment: python3.6 + selenium 3.11 + chromedriver.exe

When we parse web pages, we always encounter a large number of tags, how to pinpoint these tags, there are also many ways.

Today, when I used find_element_by_class_name to get a node object, an error was reported Compound class names not permitted.

Original code.

selected_div = driver.find_element_by_class_name(‘next-pagination next-pagination-normal next-pagination-medium medium pagination’)

Modified code.

selected_div = driver.find_element_by_css_selector(“[class=’next-pagination next-pagination-normal next-pagination-medium medium pagination’]”)

or:

selected_div = driver.find_element_by_css_selector(“.next-pagination.next-pagination-normal.next-pagination-medium.medium.pagination”)

Both pieces of code work fine to get the desired object.

To summarize.

When getting a tag object that contains multiple class names

it is recommended to use.

find_element_by_css_selector(“.xx.xxx.xxxxx”)

or

find_element_by_css_selector(“[class=’xx xxx xxxxx’]”)

How to Solve Python Error: slice indices must be integers or None or have

My code:

The content is treated as a string

content[len(content)/2:len(content)/2+5]

Error:

TypeError: slice indices must be integers or None or have an __ index__ method

Looking through a lot of data, we find that Python may be converted to floating-point number when dividing. You need to change the “/” in it to “/ /” to run it

Pyhton Regularity Error: sre_constants.error: nothing to repeat at position

 

The wrong regular expression was written

1. Number of back bands

It’s embarrassing to write “d” as “B”

>>> pattern = re.compile(r'123\b*hello')

Output:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "E:\Anacoda3\Lib\re.py", line 233, in compile
    return _compile(pattern, flags)
  File "E:\Anacoda3\Lib\re.py", line 301, in _compile
    p = sre_compile.compile(pattern, flags)
  File "E:\Anacoda3\Lib\sre_compile.py", line 562, in compile
    p = sre_parse.parse(p, flags)
  File "E:\Anacoda3\Lib\sre_parse.py", line 856, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, False)
  File "E:\Anacoda3\Lib\sre_parse.py", line 415, in _parse_sub
    itemsappend(_parse(source, state, verbose))
  File "E:\Anacoda3\Lib\sre_parse.py", line 615, in _parse
    source.tell() - here + len(this))
sre_constants.error: nothing to repeat at position 2

Error reason: because the word boundary is the word boundary, the meaning of * is the occurrence of any times, that is to say, the word can only have one boundary, and can not occur any times, so this error will be reported

How to solve the problem of potentially unsupported type in Python sqllite

Write a program to insert data into a table of sqllite, the general code is as follows:

class GameIdiom(object):
	def __init__(self, id, idiom_id=None, all_word=None, play_time=None, game_id=None):
		self.id = id
		self.idiom_id = idiom_id
		self.all_word = all_word
		self.play_time = play_time
		self.game_id = game_id
	def isNext(self, first_word):
		return self.all_word[len(self.all_word)-1] == first_word
	def copyFromIdiom(self, idiom):
		self.idiom_id = idiom.id
		self.all_word = idiom.all_word
....
class IdiomDao(object):
	def insertGameIdiom(self, gameIdiom):
		self.con.execute("insert into game_idiom(id, idiom_id, all_word, play_time, game_id) values(?,?,?,?,?)",(gameIdiom.id,gameIdiom.idiom_id,gameIdiom.all_word,gameIdiom.play_time,gameIdiom.game_id,))
...
class Game(object):
    gameIdiom = GameIdiom(id=uuid4(),play_time=time(),game_id=self.id)
    self.idiomDao.insertGame(self)

Error in execution:

sqlite3.InterfaceError: Error binding parameter 0 – probably unsupported type

Because it was the first time that Python was used to insert data into sqllite, I initially suspected that there was a problem in using this kind of placeholder method to insert data. I found no solution on the Internet for a long time. Later, I wondered if there was any problem with the value, so I printed all the values in the object to be inserted, as follows:

	def insertGameIdiom(self, gameIdiom):
		print('\n'.join(['%s:%s' % item for item in gameIdiom.__dict__.items()]))
		self.con.execute("insert into game_idiom(id, idiom_id, all_word, play_time, game_id) values(?,?,?,?,?)",(gameIdiom.id,gameIdiom.idiom_id,gameIdiom.all_word,gameIdiom.play_time,gameIdiom.game_id,))

The printed information is as follows:

id:50415712-8e3a-49bc-bb51-97fc58ead818
idiom_id:fc947044-4258-4f1f-86c1-03d1f7a08c43
all_word:111
play_time:1517109225.0413642
game_id:0c4ea9dc-470d-4ac4-af08-492d51bd68dc

Then manually set these values into the gameediom class, and call the insertgameediom method on the command line to test whether there is a problem with the values, as follows:

gameIdiom = GameIdiom('50415712-8e3a-49bc-bb51-97fc58ead818','fc947044-4258-4f1f-86c1-03d1f7a08c43','一望无际',1517109225.0413642,'0c4ea9dc-470d-4ac4-af08-492d51bd68dc')
idiomDao.insertGameIdiom(gameIdiom)

The result shows that there is no problem, which means that it is not the value in the object. This is the problem of looking at the exception information carefully, and the keyword is “potentially unsupported type”. So I thought whether it would be the parameter type problem, so I added the code of print type into the code, as follows:

	def insertGameIdiom(self, gameIdiom):
		print('\n'.join(['%s:%s' % item for item in gameIdiom.__dict__.items()]))
		print(type(gameIdiom.id))
		self.con.execute("insert into game_idiom(id, idiom_id, all_word, play_time, game_id) values(?,?,?,?,?)",(gameIdiom.id,gameIdiom.idiom_id,gameIdiom.all_word,gameIdiom.play_time,gameIdiom.game_id,))

Then execute and print the following information:

id:5e5326dd-6d46-4526-9d30-ec97177d748d
idiom_id:fc947044-4258-4f1f-86c1-03d1f7a08c43
all_word:111
play_time:1517133390.0591135
game_id:4daa77d1-fd70-4bcb-865e-8b4adcab7957
<class 'uuid.UUID'>

It is found that the type of the ID field is uuid.uuid, while the corresponding type in the database is varchar, so an error is reported. The solution is very simple, that is, when the parameter is passed in, convert UUID to STR, as follows:

gameIdiom = GameIdiom(id=str(uuid4()),play_time=time(),game_id=self.id)

Django path Error: ‘Specifying a namespace in include() without providing an app_name ‘

The specific error prompts are as follows:

django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_ name is not supported. Set the app_
name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_ name instead.

This is the error code in using Django:

Solution:

it can be seen from the include() function that this function has two parameters, an Arg and a namespace. I also have two parameters in the code, but the exception prompts that no app is provided_ Name, you also need to pass in a binary tuple, from the sixth line of code urlconf_ module, app_ Name = Arg, you can see that arg is the tuple, and give it to app_ Name is assigned a value, so we modify the code here as follows:

The modified code is as shown above, and the problem is solved

Reflection:

The error is that the include parameter is not set

How to Solve Error: [errno 99] cannot assign requested address error:

How to Solve Error: [errno 99] cannot assign requested address error:

2018-06-01 06:07:17 INFO     starting server at aws.pdflibr.com:55100
Traceback (most recent call last):
  File "/usr/local/bin/ssserver", line 11, in 

    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/1/server.py", line 74, in main
    tcp_servers.append(tcprelay.TCPRelay(a_config, dns_resolver, False))
  File "/usr/local/lib/python2.7/dist-packages/1/tcprelay.py", line 754, in __init__
    server_socket.bind(sa)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address

The most important is the last sentence: socket. Error: [errno 99] cannot assign requested address

You need to server:0.0.0.0 , which will solve the problem of Indescribability by restarting once more

{
"server":"0.0.0.0",
"server_port":8989,
"local_address":"127.0.0.1",
"local_port":1080,
"password":"password",
"timeout":300,
"method":"aes-256-cfb",
"fast_open": false
}

How to Solve Python socket:[Errno 32] Broken pipe

This error occurs when the client side closes its current socket connection to your server side, but your server side is busy sending data to a socket that is already disconnected.

Here is the solution given by stackoverflow:

Your server process has received a SIGPIPE writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn’t wait till all the data from the server is received and simply closes a socket (using close function). In a C program you would normally try setting to ignore SIGPIPE signal or setting a dummy signal handler for it. In this case a simple error will be returned when writing to a closed socket. In your case a python seems to throw an exception that can be handled as a premature disconnect of the client.

Here is the python implementation:

import socket
def hack_fileobject_close():
    if getattr(socket._fileobject.close, '__hacked__', None):
        return
    old_close = socket._fileobject.close
    def new_close(self, *p, **kw):
        try:
            return old_close(self, *p, **kw)                                                                                                                                    
        except Exception, e:
            print("Ignore %s." % str(e))
    new_close.__hacked__ = True
    socket._fileobject.close = new_close
hack_fileobject_close()

[773]smtplib.SMTPServerDisconnected: Connection unexpectedly closed

 

Output:
D:\Python\python3.exe "D:/PyCharm files/face/raspberry/smtp.py"
Traceback (most recent call last):
 File "D:/PyCharm files/face/raspberry/smtp.py", line 43, in <module>
  smtp.login( username, password )                #Login Server
 File "D:\Python\lib\smtplib.py", line 721, in login
  initial_response_ok=initial_response_ok)
 File "D:\Python\lib\smtplib.py", line 631, in auth
  (code, resp) = self.docmd("AUTH", mechanism + " " + response)
 File "D:\Python\lib\smtplib.py", line 421, in docmd
  return self.getreply()
 File "D:\Python\lib\smtplib.py", line 394, in getreply
  raise SMTPServerDisconnected("Connection unexpectedly closed")

smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Solution:

Add two lines of code in front of SMTP. Login (user name, password) to send the mail successfully. The code added is as follows:

smtp.ehlo()
smtp.starttls()

The above solution can be solved in win server, but not in Linux server

Secure mail needs to be sent through SSL

server = smtplib.SMTP()
server.connect(email_host,25)

Exception thrown:

smtplib.SMTPServerDisconnected: Connection unexpectedly closed

QQ mailbox supports secure e-mail and needs to send e-mail through SSL: when using the standard 25 port to connect to the SMTP server, it uses plaintext transmission, and the whole process of sending e-mail may be eavesdropped. To send e-mail more safely, you can encrypt the SMTP session, which is to create a SSL secure connection first, and then use the SMTP protocol to send e-mail

Modification code:

server = smtplib.SMTP_SSL()
server.connect(email_host,465)# Enable SSL messaging, port is usually 465