【问题标题】:How to use utf-8 characters in dryscrape in Python?如何在 Python 的 dryscrape 中使用 utf-8 字符?
【发布时间】:2017-12-20 06:38:25
【问题描述】:

我需要在set dryscrape 方法中使用 utf-8 字符。但运行后显示此错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)

我的代码(例如):

site = dryscrape.Session()
site.visit("https://www.website.com")
search = site.at_xpath('//*[@name="search"]')
search.set(u'فارسی')
search.form().submit()

同样u'فارسی'改成search.set(unicode('فارسی', 'utf-8')),但是显示这个错误。

【问题讨论】:

  • 你试过search.set(u'فارسی'.encode('utf-8'))吗?说真的,您应该使用 Python 3。它具有更好的 Unicode 处理能力。同时,看看Pragmatic Unicode,它是由 SO 老手 Ned Batchelder 编写的。
  • 第一:How do you know the response is Unicode?。第二:Your application code cannot be UTF-8(不会在您的输入中提供相等性读取。)
  • @PM2Ring ,嗨,我尝试search.set(u'فارسی'.encode('utf-8')) 但显示此错误。我使用python 2.7。 :(
  • @dsgdfg ,嗨,我在第一行添加了# coding=utf-8。对不起,我不太懂英语。请解释更多...
  • search.set("فارسی") 。您的编码类型是iso8859-6(但默认是ascii)。 import locale; print locale.getdefaultlocale() 如果输出没有 UTF-8,请在应用程序的开头更改默认的本地编码形状。如果您已经有本地编码 UTF-8,则无需在 Python 应用程序的开头写入任何内容!

标签: python utf-8 dryscrape


【解决方案1】:

它非常简单...这种方法与谷歌完美配合。如果您知道 url 婴儿车,也可以尝试其他任何人

import dryscrape as d
d.start_xvfb()
br = d.Session()
import urllib.parse
query = urllib.parse.quote("فارسی")
print(query)  #it prints : '%D9%81%D8%A7%D8%B1%D8%B3%DB%8C'
Url = "http://google.com/search?q="+query
br.visit(Url)
print(br.xpath('//title')[0].text())
#it prints : Google Search - فارسی
#You can also check it with br.render("url_screenshot.png")

【讨论】:

    猜你喜欢
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 2014-07-11
    • 2019-09-17
    相关资源
    最近更新 更多