Python2.7硒错误

时间:2016-01-24 06:39:10

标签: python python-2.7 selenium text

所以我最近因为无法使用py2exe而从python 3.5转移了python 2.7,但是我在3.5上运行了这个脚本但是现在我在2.7中得到了一个错误,如果你们能帮我一个帮助我重新开始这个问题,它很棒。

from selenium import webdriver
import time
import random



print("\n")
user_input = raw_input("Username: ")


##########################################################
path = r"C:\Users\Skid\Desktop\chromedriver.exe"
driver = webdriver.Chrome(path)
##########################################################



##########################################################

text_file = open(user_input+ str(random.random()) + ".txt", "w")
text_file.write("GoogleSearch:\n\n")
print("Google results:\n")
driver.get("https://www.google.com/#q=" + user_input)
for n in range(10):
    try:
        driver.find_element_by_xpath("//*[@id='pnnext']/span[2]").click()
    except: 
        pass
    time.sleep(5)
    posts2 = driver.find_elements_by_class_name("_Rm")
    for post2 in posts2:
        print(post2.text)
        text_file.write(post2.text + "\n")



print("\n")
print("Pipl results:\n\n")
text_file.write("\n\n")
text_file.write("Pipl results:\n\n")
driver.get("https://pipl.com/search/?q=" + user_input + "&l=&sloc=&in=5")
posts1 = driver.find_elements_by_class_name("line1")
for post1 in posts1:
    print(post1.text)
    text_file.write(post1.text + "\n")

time.sleep(1)
driver.close()

Traceback (most recent call last):
  File "C:/Users/Skid/PycharmProjects/untitled/2nd.py", line 34, in <module>
    text_file.write(post2.text + "\n")
UnicodeEncodeError: 'ascii' codec can't encode character u'\u203a' in position 23: ordinal not in range(128)

1 个答案:

答案 0 :(得分:0)

尝试在print(post2.text)

之后插入这些行
A=post2.text

A=A.encode('ascii','ignore')

而不是text_file.write(post2.text + "\n")text_file.write(A + "\n")

它对我有用。

调试下一个按钮问题请尝试以下代码:

for n in range(10):
nextbutton = 0
try:
    nextbutton = driver.find_element_by_xpath("//*[@id='pnnext']/span[2]")
    if nextbutton !=0 :
        nextbutton.click()
except: pass
time.sleep(5)
if nextbutton != 0 or n==0:
    posts2 = driver.find_elements_by_class_name("_Rm")
    for post2 in posts2:
        print(post2.text)
        A=post2.text
        A=A.encode('ascii','ignore')
        text_file.write(A + "\n")