【发布时间】:2020-07-20 16:30:30
【问题描述】:
我尝试解码存在的 URL if,但它似乎不起作用:
这是如下所示的错误:
Traceback (most recent call last):
File "E:\Users\Francbicon\Desktop\Bots\Master Copy\Shopee Endless Loop.py", line 185, in <module>
clickpy()
File "E:\Users\Francabicon\Desktop\Bots\Master Copy\Shopee Endless Loop.py", line 75, in clickpy
print(all_urls)
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 878-878: Non-BMP character not supported in Tk
这是整个代码:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import csv
import urllib.parse
import time
url = 'https://shopee.com.my/search?keyword=mattress'
driver = webdriver.Chrome(executable_path=r'E:/users/Asashin/Desktop/Bots/others/chromedriver.exe')
driver.get(url)
time.sleep(0.8)
# Select language
driver.find_element_by_xpath('//div[@class="language-selection__list"]/button').click()
time.sleep(3)
# Scroll a few times to load all items
def clickpy():
for x in range(10):
driver.execute_script("window.scrollBy(0,300)")
time.sleep(0.1)
# Get all links (without clicking)
all_items = driver.find_elements_by_xpath('//a[@data-sqe="link"]')
all_urls = []
s=["-Dr.Alstone-","-Dr.-Alstone-","-Lutfy-Paris-"]
for item in all_items:
# This give you whole url of the anchor tag
url = item.get_attribute('href')
if "-Dr.Alstone-" in url:
continue
else:
if "-Dr.-Alstone-" in url:
continue
else:
if "/Dr.Alstone-" in url:
continue
else:
if "-Simoni-" in url:
continue
else:
if "-Lütfy-" in url:
continue
else:
# You need to remove the preceding values in order to verify href later for clicking
urlfinal=url.split('https://shopee.com.my')[1]
c = urllib.parse.unquote(urlfinal)
all_urls.append(c)
print(all_urls)
a= len(all_urls)
print('len:' + str(a))
这是我尝试过的方法:try and except、if-else 和正常循环,但似乎效果不佳。错误不断弹出。
我该如何解决?
【问题讨论】:
-
如果这是完整的代码,那么你什么时候运行
clickpy()?我在代码中看不到它,但错误表明它会产生问题。 -
当我运行
clickpy()然后它在 Linux 上正常工作。也许问题不是代码,而是您用来运行它的工具。我看到Tk出错了。您使用Tk、tkinter或IDLE使用tkinter(使用Tk)?如果您直接在控制台中运行它或使用其他编辑器/IDE(即 PyCharm),它可能会正常工作 -
@furas 我不使用任何 tk 这是一个用于获取 url 链接的 selenium webdriver 机器人,但我最近添加了“import urllib.parse”然后错误来了。
-
从
all_urls列表中打印其中一个链接有问题 - 您可以使用for-loop 分别打印每个 url 以查看哪个有问题。您可以在使用urllib.parse.unquote()之前打印 url - 也许它会显示更多内容。您也可以使用print(repl(url)),它应该使用十六进制代码而不是 ascii 字符。
标签: python selenium selenium-webdriver decode ucs2