【问题标题】:Python2.7 selenium errorsPython2.7 硒错误
【发布时间】:2016-01-24 06:39:09
【问题描述】:

因此,由于无法使用 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)

【问题讨论】:

    标签: python python-2.7 selenium text


    【解决方案1】:

    尝试在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")
    

    【讨论】:

    • 喜欢这个? print(post2.text) text_file.write(post2.text + "\n") A=post2.text A=A.encode('ascii','ignore') 我这样做了,但是没有用 嗯
    • 该死的,谢谢,这很奇怪。如果没有更多按钮可以点击,知道如何让它停止吗?
    • “没有更多的按钮可以点击”是什么意思?
    • 比如,如果你在 google 上搜索如此特殊的东西,只有 4 个下一步按钮可以点击,因为我有这个问题。只有 4 页,在最后一页它只是循环
    • Skid 我已经添加了解决下一个按钮问题结帐的代码
    猜你喜欢
    • 2012-03-05
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2017-06-01
    • 2016-12-27
    相关资源
    最近更新 更多