【问题标题】:ValueError: can only parse strings pythonValueError:只能解析字符串python
【发布时间】:2015-10-19 22:43:29
【问题描述】:

我正在尝试使用 xpath 收集一堆链接,这些链接需要从下一页抓取,但是,我不断收到只能解析字符串的错误?我尝试查看 lk 的类型,并且在我投射它之后它是一个字符串?似乎有什么问题?

 def unicode_to_string(types):
   try:
      types = unicodedata.normalize("NFKD", types).encode('ascii', 'ignore')
      return types
  except:
      return types

def getData():
  req = "http://analytical360.com/access-points"
  page = urllib2.urlopen(req)
  tree = etree.HTML(page.read())  
  i = 0
   for lk in tree.xpath('//a[@class="sabai-file sabai-file-image sabai-file-type-jpg "]//@href'):
      print "Scraping Vendor #" + str(i)
      trees = etree.HTML(urllib2.urlopen(unicode_to_string(lk))) 
      for ll in trees.xpath('//table[@id="archived"]//tr//td//a//@href'):
         final = etree.HTML(urllib2.urlopen(unicode_to_string(ll)))

【问题讨论】:

  • 你能发布完整的回溯吗?
  • 在下一部分你有page = urllib2.urlopen(req); etree.HTML(page.read()) 在下一部分你有etree.HTML(urllib2.urlopen(unicode_to_string(ll))) 在urlopen 返回对象上缺少.read()
  • 您需要将字符串而不是 urllib2.urlopen 对象传递给unicode_to_string

标签: python lxml screen-scraping


【解决方案1】:

你应该传入字符串而不是 urllib2.orlopen。

也许像这样更改代码:

trees = etree.HTML(urllib2.urlopen(unicode_to_string(lk)).read()) 
    for i, ll in enumerate(trees.xpath('//table[@id="archived"]//tr//td//a//@href')):
        final = etree.HTML(urllib2.urlopen(unicode_to_string(ll)).read())

另外,你似乎没有增加i

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多